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.
Code
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
Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.