Read input stream twice Read input stream twice java java

Read input stream twice


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();// eitherwhile (needToReadAgain) {    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);    yourReadMethodHere(bais);}// orByteArrayInputStream bais = new ByteArrayInputStream(bytes);while (needToReadAgain) {    bais.reset();    yourReadMethodHere(bais);}


Depending on where the InputStream is coming from, you might not be able to reset it. You can check if mark() and reset() are supported using markSupported().

If it is, you can call reset() on the InputStream to return to the beginning. If not, you need to read the InputStream from the source again.


if your InputStream support using mark, then you can mark() your inputStream and then reset() it . if your InputStrem doesn't support mark then you can use the class java.io.BufferedInputStream,so you can embed your stream inside a BufferedInputStream like this

    InputStream bufferdInputStream = new BufferedInputStream(yourInputStream);    bufferdInputStream.mark(some_value);    //read your bufferdInputStream     bufferdInputStream.reset();    //read it again