如何克隆InputStream? [英] How to clone an InputStream?

查看:166
本文介绍了如何克隆InputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个InputStream,我传递给一个方法来做一些处理。我将在其他方法中使用相同的InputStream,但在第一次处理之后,InputStream似乎在方法内部关闭。

I have a InputStream that I pass to a method to do some processing. I will use the same InputStream in other method, but after the first processing, the InputStream appears be closed inside the method.

如何克隆InputStream以发送到关闭他的方法?还有另一个解决方案吗?

How I can clone the InputStream to send to the method that closes him? There is another solution?

编辑:关闭InputStream的方法是来自lib的外部方法。我无法控制是否关闭。

the methods that closes the InputStream is an external method from a lib. I dont have control about closing or not.

private String getContent(HttpURLConnection con) {
    InputStream content = null;
    String charset = "";
    try {
        content = con.getInputStream();
        CloseShieldInputStream csContent = new CloseShieldInputStream(content);
        charset = getCharset(csContent);            
        return  IOUtils.toString(content,charset);
    } catch (Exception e) {
        System.out.println("Error downloading page: " + e);
        return null;
    }
}

private String getCharset(InputStream content) {
    try {
        Source parser = new Source(content);
        return parser.getEncoding();
    } catch (Exception e) {
        System.out.println("Error determining charset: " + e);
        return "UTF-8";
    }
}


推荐答案

如果你想要做的就是多次读取相同的信息,并且输入数据足够小以适应内存,你可以将数据从 InputStream 复制到< a href =http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html\"rel =noreferrer> ByteArrayOutputStream 。

If all you want to do is read the same information more than once, and the input data is small enough to fit into memory, you can copy the data from your InputStream to a ByteArrayOutputStream.

然后你可以获得相关的字节数组并打开尽可能多的克隆 ByteArrayInputStream 你喜欢的。

Then you can obtain the associated array of bytes and open as many "cloned" ByteArrayInputStreams as you like.

ByteArrayOutputStream baos = new ByteArrayOutputStream();

// Fake code simulating the copy
// You can generally do better with nio if you need...
// And please, unlike me, do something about the Exceptions :D
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1 ) {
    baos.write(buffer, 0, len);
}
baos.flush();

// Open new InputStreams using the recorded bytes
// Can be repeated as many times as you wish
InputStream is1 = new ByteArrayInputStream(baos.toByteArray()); 
InputStream is2 = new ByteArrayInputStream(baos.toByteArray()); 

但是如果你真的需要保持原始流开放以接收新数据,那么你需要跟踪此外部 close()方法并阻止以某种方式调用它。

But if you really need to keep the original stream open to receive new data, then you will need to track this external close() method and prevent it from being called somehow.

这篇关于如何克隆InputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆