O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required