Saturday Aug 31

Key Concepts

Reading an InputStream multiple times

PDFPrintE-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 java.io.InputStream 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

import java.io.IOException;
import java.io.InputStream;
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;
    }
    @Override
    public void close() throws IOException {
        decorated.reset();
    }
    @Override
    public int read() throws IOException {
        return decorated.read();
    }
}

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
Refresh

Java Tutorial on Facebook