Read a stream multiple times

InputStreams are for definition read-once classes. Once you have consumed the data you can't read them again.

The following classes let user read a stream multiple times. The content of the stream is cached first in memory, and then to disk.

RandomAccessInputStream

This class is a filter (it takes an InputStream in the constructor and exposes all the data of the stream in a transparent way).

It adds the following functionality to the wrapped InputStream:

  • the ability to be read multiple times.
  • seek() to a random position.
  • Support the mark() and reset() methods.
Caching of data is done in a Store, so every application can choose where to store its temporary data. Default implementation cache first 64K in memory and then on disk.

How to read two times the content of a file:

 InputStream source=... //some data to be read multiple times.
 final RandomAccessInputStream ris = new RandomAccessInputStream(source);
 final byte[] b = new byte[5];
 ris.read(b);
 //seek back to beginning of file
 ris.seek(0);
 final byte[] b1 = new byte[5];
 ris.read(b1);
 //arrays b and b1 are equals.

For further information read the api javadoc.