InputStream is abstract and does not expose (neither do its children) internal data objects. So the only way to "deep copy" the InputStream is to create ByteArrayOutputStream and after doing read() on InputStream, write() this data to ByteArrayOutputStream. Then do:
newStream = new ByteArrayInputStream(byteArrayOutputStream.toArray());
If you are using mark() on your InputStream then indeed you can not reverse this. This makes your stream "consumed".
To "reuse" your InputStream avoid using mark() and then at the end of reading call reset(). You will be then reading from beginning of the stream.
Edited:
BTW, IOUtils uses this simple code snippet to copy InputStream:
public static int copy(InputStream input, OutputStream output) throws IOException{
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
发布评论
评论(1)
InputStream 是抽象的,不公开(其子级也不公开)内部数据对象。因此,“深度复制”InputStream 的唯一方法是创建 ByteArrayOutputStream,并在对 InputStream 执行 read() 后,将此数据 write() 到 ByteArrayOutputStream。然后做:
如果您在 InputStream 上使用
mark()
那么您确实无法逆转这一点。这会使您的流被“消耗”。要“重用”InputStream,请避免使用mark(),然后在读取结束时调用reset()。然后您将从流的开头开始阅读。
已编辑:
顺便说一句,IOUtils 使用这个简单的代码片段来复制 InputStream:
了解更多:http://kickjava.com/src/org/apache/commons/io/CopyUtils.java.htm#ixzz13ymaCX9m
InputStream is abstract and does not expose (neither do its children) internal data objects. So the only way to "deep copy" the InputStream is to create ByteArrayOutputStream and after doing read() on InputStream, write() this data to ByteArrayOutputStream. Then do:
If you are using
mark()
on your InputStream then indeed you can not reverse this. This makes your stream "consumed".To "reuse" your InputStream avoid using mark() and then at the end of reading call reset(). You will be then reading from beginning of the stream.
Edited:
BTW, IOUtils uses this simple code snippet to copy InputStream:
Read more: http://kickjava.com/src/org/apache/commons/io/CopyUtils.java.htm#ixzz13ymaCX9m