BufferedReader Mark And Reset Lookahead

Peek ahead with mark and reset a BufferedReader to re-read characters after deciding how to parse them; exceeding readAheadLimit invalidates the mark.

JavaData Integrity

Code

snippet
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class NumberScan {

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new StringReader("x42y7z"));

        // 前窥 lookahead:mark(64) 后最多读 64 个字符仍可 reset 回来
        in.mark(64);
        int first = in.read();   // 'x'
        int second = in.read();  // '4'
        int third = in.read();   // '2'  → 确认是数字,回退重新整段解析
        System.out.println("peeked: " + (char) first + (char) second + (char) third);

        // reset 回到 mark 点:'x' 会再次被读到
        in.reset();
        System.out.println("resets to: " + (char) in.read());

        StringBuilder rest = new StringBuilder();
        int c;
        while ((c = in.read()) != -1) {
            rest.append((char) c);
        }
        System.out.println("rest: " + rest);

        // 超过 readAheadLimit 会让 mark 失效:只读 2 个上限却读走 5 个字符
        BufferedReader tiny = new BufferedReader(new StringReader("abcdef"), 2);
        tiny.mark(2);
        for (int i = 0; i < 5; i++) {
            tiny.read();
        }
        try {
            tiny.reset();
            System.out.println("reset ok");
        } catch (IOException expired) {
            System.out.println("mark expired: " + expired.getMessage());
        }
    }
}

How it works

BufferedReader Mark And Reset Lookahead comes down to the class NumberScan.

The cycling part of this snippet is while ((c = in.read()) != -1).

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

Output lines are prefixed (peeked:, resets to:, rest:), making each step’s impact easy to trace.

Key statements worth quoting

BufferedReader tiny = new BufferedReader(new StringReader("abcdef"), 2);
BufferedReader in = new BufferedReader(new StringReader("x42y7z"));
int third = in.read();   // '2'  → 确认是数字,回退重新整段解析
System.out.println("peeked: " + (char) first + (char) second + (char) third);

Interactive Tools for This Topic

FAQ

What does BufferedReader Mark And Reset Lookahead print when run?
No setup needed: run the file and look for labeled lines like `peeked:`, `resets to:`, `rest:` in the output.