StreamTokenizer Splits Words And Numbers

Break a log-style line into word, number, quoted phrase and raw character tokens with StreamTokenizer, and report line ends via lineno once enabled.

JavaCli Tooling

Code

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

public class LogTokenizer {

    public static void main(String[] args) throws IOException {
        // 默认词法:字母成词、数字成数、引号包短语、'/' 开注释,'-' 等原样吐出
        StreamTokenizer in = new StreamTokenizer(new StringReader(
                "order 42 status \"in transit\" weight 3.5 // notes"));

        int t;
        while ((t = in.nextToken()) != StreamTokenizer.TT_EOF) {
            switch (t) {
                case StreamTokenizer.TT_NUMBER -> System.out.println("number: " + in.nval);
                case StreamTokenizer.TT_WORD -> System.out.println("word: " + in.sval);
                default -> System.out.println("char: " + (char) t);
            }
        }

        // 行号由 lineno() 维护;eolIsSignificant(true) 才把换行当 TT_EOL 报告
        StreamTokenizer lines = new StreamTokenizer(new StringReader("7 idle\n42 active"));
        lines.eolIsSignificant(true);
        while ((t = lines.nextToken()) != StreamTokenizer.TT_EOF) {
            if (t == StreamTokenizer.TT_EOL) {
                System.out.println("end of line " + lines.lineno());
            } else if (t == StreamTokenizer.TT_NUMBER) {
                System.out.println("number: " + lines.nval);
            } else {
                System.out.println("word: " + lines.sval);
            }
        }
    }
}

How it works

The moving parts are the class LogTokenizer.

Repetition is confined to while ((t = in.nextToken()) != StreamTokenizer.TT_EOF) — the rest of the file is straight-line.

What to watch for

  • No dependency resolution happens here; the toolchain alone suffices.

Using it

The demo output is labeled (number:, word:, char:), so each printed line points back to the operation that produced it.

The key statements that remain

StreamTokenizer lines = new StreamTokenizer(new StringReader("7 idle\n42 active"));
lines.eolIsSignificant(true);

Interactive Tools for This Topic

FAQ

What does StreamTokenizer Splits Words And Numbers print when run?
Invoke the file as-is — the `number:`, `word:`, `char:` prefixes identify which step printed each line.