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

I think the answers referencing a FileChannel are on the mark .

Here’s a sample implementation of an input stream that encapsulates this functionality. It uses delegation, so it’s not a true FileInputStream, but it is an InputStream, which is usually sufficient. One could similarly extend FileInputStream if that’s a requirement.

Not tested, use at your own risk 🙂

public class MarkableFileInputStream extends FilterInputStream {
    private FileChannel myFileChannel;
    private long mark = -1;

    public MarkableFileInputStream(FileInputStream fis) {
        super(fis);
        myFileChannel = fis.getChannel();
    }

    @Override
    public boolean markSupported() {
        return true;
    }

    @Override
    public synchronized void mark(int readlimit) {
        try {
            mark = myFileChannel.position();
        } catch (IOException ex) {
            mark = -1;
        }
    }

    @Override
    public synchronized void reset() throws IOException {
        if (mark == -1) {
            throw new IOException("not marked");
        }
        myFileChannel.position(mark);
    }
}

Leave a Comment