Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this questionI would like to know how to make a deep copy of an InputStream
.
I know that it can be done with IOUti开发者_如何学JAVAls packages, but I would like to avoid them if possible. Does anyone know an alternate way?
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;
}
Read more: http://kickjava.com/src/org/apache/commons/io/CopyUtils.java.htm#ixzz13ymaCX9m
精彩评论