Search code examples
javainputstream

Read input stream twice


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 thought it would be faster to use the same stream instead of starting a new stream to the downloaded content and then read it again.


Solution

  • 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);
    }
    

    (WARNING 06/06/24 - this copies the stream to a byte array. The question spoke about downloading an image from the web, and so I made the reasonable assumption that the image bytes are few enough to be 'saved' to memory. The approach shown here would likely not be appropriate for large streams, and certainly not appropriate for infinite streams. In those cases, the approach shown here would run out of memory at some point before completing.)