Read stream twice

Warpzit picture Warpzit · Feb 29, 2012 · Viewed 106.9k times · Source

How do you read the same inputstream twice? Is it possible to copy it somehow?

I need to get a image from web, save it locally and then return the saved image. I just tought it would be faster to use the same stream instead of starting a new stream to the downloaded content and then read it again.

Answer

Paul Grime picture Paul Grime · Feb 29, 2012

You can use org.apache.commons.io.IOUtils.copy to copy the contents of the InputStream to a byte array, and then repeatedly read from the byte array using a ByteArrayInputStream. E.g.:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(in, baos);
byte[] bytes = baos.toByteArray();

// either
while (needToReadAgain) {
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    yourReadMethodHere(bais);
}

// or
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
while (needToReadAgain) {
    bais.reset();
    yourReadMethodHere(bais);
}