Track Line Numbers With LineNumberReader
Read text with LineNumberReader, set line numbers before parsing, and use mark and reset to reparse a section with correct numbering.
Code
import java.io.LineNumberReader;
import java.io.StringReader;
public class LineNumberReaderDemo {
public static void main(String[] args) throws Exception {
String text = "alpha\nbeta\ngamma\ndelta\n";
LineNumberReader reader = new LineNumberReader(new StringReader(text));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(reader.getLineNumber() + ": " + line);
}
System.out.println("final line number: " + reader.getLineNumber());
// setLineNumber 只影响报告值,不改变读取位置
reader.setLineNumber(100);
reader.close();
// mark/reset 同时恢复位置与行号
LineNumberReader marked = new LineNumberReader(new StringReader(text), 64);
marked.setLineNumber(10);
System.out.println("first: " + marked.readLine() + " at " + marked.getLineNumber());
marked.mark(64);
System.out.println("second: " + marked.readLine() + " at " + marked.getLineNumber());
marked.reset();
System.out.println("re-read: " + marked.readLine() + " at " + marked.getLineNumber());
marked.close();
}
}What the code does
Track Line Numbers With LineNumberReader comes down to the class LineNumberReaderDemo.
Repetition is confined to while ((line = reader.readLine()) != null) — the rest of the file is straight-line.
Using it
Output lines are prefixed (final line number:, first:, second:), making each step’s effect easy to spot.
Key statements
LineNumberReader marked = new LineNumberReader(new StringReader(text), 64);
LineNumberReader reader = new LineNumberReader(new StringReader(text));
String text = "alpha\nbeta\ngamma\ndelta\n";
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.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.Roman Numeral ConverterConvert integers between 1 and 3999 to Roman numerals and back, rejecting malformed numeral forms.Scientific Notation ConverterConvert numbers between plain decimal and scientific notation, optionally fixing the significant digits and splitting out the mantissa and exponent.
FAQ
- What does Track Line Numbers With LineNumberReader print when run?
- Invoke the file as-is — the `final line number:`, `first:`, `second:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.