Saturday Aug 31

Reading an InputStream multiple times

PDF Print E-mail
Friday, 22 February 2013 08:16
AddThis Social Bookmark Button

Reusable inputStream multiple read

Sometimes you need to be able to re-use a multiple times.You can off course provide multiple times the same InputStream or you can play the mark method if your inputStream support it.

In this article we will not discuss about the buffering option and other advanced solution we will just provide a very simple and efficient way to support multiple reads by reseting the inputstream.

We will create a wrapper around our inputStream and instead of closing the inputStream we will make a reset to reinitialize the inputstream for another reading.

InputStream multiple read markSupported and reset method usaged

public class ResetOnCloseInputStream extends InputStream {
    private final InputStream decorated;
    public ResetOnCloseInputStream(InputStream inputStream) {
        if (!inputStream.markSupported()) {
            throw new IllegalArgumentException("marking not supported");
        inputStream.mark( 1 << 32);
        decorated = inputStream;
    public void close() throws IOException {
    public int read() throws IOException {

The constructor evaluate if the provided input stream is supporting the mark and reset method for this particular input stream instance.

Some examples:

Class Mark supported
ByteArrayInputStream Yes
BufferedInputStream Yes
PushbackInputStream No
FileInputStream No
SocketInputStream No
ObjectInputStream No

The mark method takes as an argument a readlimit who tells the input stream to allow that many bytes to read before the mark pesition gets invalidated.

Tags: multiple , public , ioexception , throws , @override , times , inputstream , provide , wrapper

Add comment

Security code

Java Tutorial on Facebook