Take the 2-minute tour ×

I would like to know how to make a deep copy of an InputStream.

I know that it can be done with IOUtils packages, but I would like to avoid them if possible. Does anyone know an alternate way?

share|improve this question
Why do you want to do that? Afaik you can't read twice from one stream. –  thejh Oct 31 '10 at 17:39
For some odd reason I think my stream is consumed once I used it. So to make sur that is not the case I would like to make a deep copy. I am working with android and getting images from a webservice using REST architecture. –  Spredzy Oct 31 '10 at 17:42
Why don't you show us the relevant code and explain the actual problem you're having? –  Matt Ball Oct 31 '10 at 18:01
@dacwe - en.wikipedia.org/wiki/Object_copy –  Johnbabu Koppolu Oct 31 '10 at 21:51
@johnbk yes, it makes no sense, what if the inputstream does not have an end? –  dacwe Nov 1 '10 at 7:02
show 1 more comment

1 Answer

up vote 13 down vote accepted

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.


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;
         output.write(buffer, 0, n);
         count += n;
     return count;

Read more: http://kickjava.com/src/org/apache/commons/io/CopyUtils.java.htm#ixzz13ymaCX9m

share|improve this answer
add comment

Your Answer


