java file input with rewind()/reset() capability

Viewed 48107

I need to write a function that takes in some kind of input stream thing (e.g. an InputStream or a FileChannel) in order to read a large file in two passes: once to precompute some capacities, and second to do the "real" work. I do not want the whole file loaded into memory at once (unless it is small).

Is there an appropriate Java class that provides this capability? FileInputStream itself does not support mark()/reset(). BufferedInputStream does, I think, but I'm not clear whether it has to store the whole file to do this.

C is so simple, you just use fseek(), ftell(), and rewind(). :-(

9 Answers

BufferedInputStream supports mark by buffering the content in memory. It is best reserved for relatively small look-aheads of a predictable size.

Instead, RandomAccessFile can be used directly, or it could serve as the basis for a concrete InputStream, extended with a rewind() method.

Alternatively, a new FileInputStream can be opened for each pass.

java.nio.channels.FileChannel has a method position(long) to reset the position back to zero like fseek() in C.

Check out java.io.RandomAccessFile

PushbackInputStream will also work, as long as you know how many characters you want to be able to rewind

Related