Course contentsShow
← Java
Lesson 1965 of 2,87040. File I/O: Character StreamsFree lesson

mark() and reset(): Repositioning Character Streams

Understanding how to mark positions in character streams and reset back to them, when supported.

mark() and reset(): Repositioning Character Streams

You'll learn how to bookmark a position in a character stream and jump back to it later, when the stream supports this feature.

The Core Idea

Imagine reading a book and placing a bookmark on a page so you can flip forward, then return to that exact spot. mark() and reset() provide similar functionality for character streams.

When you call mark() on a Reader, you're placing a bookmark at the current reading position. Later, calling reset() returns you to that marked position, allowing you to re-read the same characters.

Why This Matters

This feature is useful when you need to:

  • Peek ahead in a stream to determine how to process data
  • Parse ambiguous input where you might need to backtrack
  • Implement lookahead logic without consuming the stream permanently

Not All Streams Support Marking

Before using mark() and reset(), you must check if the stream supports them by calling markSupported():

Reader reader = // ... some Reader
if (reader.markSupported()) {
    // Safe to use mark() and reset()
}

How mark() Works

The mark(int readAheadLimit) method takes a parameter specifying how many characters you might read before resetting. The stream must preserve at least this many characters in memory:

reader.mark(100); // Mark current position, promise to reset within 100 chars

If you exceed this limit before calling reset(), the mark may become invalid, and reset() could throw an IOException.

Key Takeaway: mark() bookmarks your position in a character stream, and reset() returns you there—but only if markSupported() returns true and you stay within the read-ahead limit.