Read input stream twice
Solution 1:
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);
}
Solution 2:
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.