Hi guys,
I would like to know how to make a deep copy of an InputStream?
I know that we can do it with IOUtils packages but I would like to avoid it if possible. Does anyone know how to make it please?
Thank you !
Hi guys,
I would like to know how to make a deep copy of an InputStream?
I know that we can do it with IOUtils packages but I would like to avoid it if possible. Does anyone know how to make it please?
Thank you !
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