PushbackReader Peeks And Unreads

Build a tiny lexer with PushbackReader: read one char, classify it, and unread it when the next loop must decide all over again.

JavaCli Tooling

Code

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

public class TinyLexer {

    // 词法器的标准手法:先读出一个字符分类,不属于当前词就退回
    public static void main(String[] args) throws IOException {
        try (PushbackReader in = new PushbackReader(new StringReader("order42 price7"))) {
            int c;
            while ((c = in.read()) != -1) {
                if (Character.isLetter(c)) {
                    StringBuilder word = new StringBuilder().append((char) c);
                    while (Character.isLetter(c = in.read())) {
                        word.append((char) c);
                    }
                    if (c != -1) {
                        in.unread(c); // 非字母退回,让下一轮重新分类
                    }
                    System.out.println("word : " + word);
                } else if (Character.isDigit(c)) {
                    StringBuilder num = new StringBuilder().append((char) c);
                    while (Character.isDigit(c = in.read())) {
                        num.append((char) c);
                    }
                    if (c != -1) {
                        in.unread(c); // EOF 不必退回
                    }
                    System.out.println("number: " + num);
                }
            }
        }
    }
}

The lexer pattern

PushbackReader over a StringReader lets the loop read one character, classify it (letter or digit), and push it back with in.unread(c) when it turns out to belong to the next token. The default pushback buffer of one character is exactly enough for this single-character lookahead.

Two token classes

Letters accumulate into a word printed as word : order (then price); digits accumulate into a number printed as number: 42 (then 7). The terminating character of each run is unread unless it is EOF, so the outer while loop can reclassify it.

Why not regex

For two token kinds the hand-rolled loop is explicit and dependency-free; unread() is the primitive that makes single-character backtracking possible.

Interactive Tools for This Topic

FAQ

Why is unread() not called on EOF?
Reading -1 means the stream is exhausted; pushing back EOF would be pointless, so the code guards the unread with c != -1.
How large is the default pushback buffer?
One character, which is exactly the single-character lookahead this lexer needs; larger buffers are available via the two-arg constructor.