Marking and Resetting

It’s often useful to be able to read a few bytes and then back up and reread them. For example, in a Java compiler, you don’t know for sure whether you’re reading the token <, <<, or <<= until you’ve read one too many characters. It would be useful to be able to back up and reread the token once you know which token you’ve read. Compiler design and other parsing problems provide many more examples, and this need occurs in other domains as well.

Some (but not all) input streams allow you to mark a particular position in the stream and then return to it. Three methods in the java.io.InputStream class handle marking and resetting:

public synchronized void mark(int readLimit)
public synchronized void reset() throws IOException
public boolean markSupported()

The boolean markSupported() method returns true if this stream supports marking and false if it doesn’t. If marking is not supported, reset() throws an IOException and mark() does nothing. Assuming the stream does support marking, the mark() method places a bookmark at the current position in the stream. You can rewind the stream to this position later with reset() as long as you haven’t read more than readLimit bytes. There can be only one mark in the stream at any given time. Marking a second location erases the first mark.

The only two input stream classes in java.io that always support marking are BufferedInputStream (of which System.in is an instance) and ByteArrayInputStream. However, other input streams, ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.