LineNumberReader class
A buffered character-input stream that keeps track of line numbers.
LineNumberReader has setLineNumber(int) and getLineNumber() for setting and getting the current line number respectively. By default, line numbering begins at 0.
Constructor | Summary | LineNumberReader(Reader in) Create a new line-numbering reader, using the default input-buffer size. LineNumberReader(Reader in, int sz) Create a new line-numbering reader, reading characters into a buffer of the given size.
---|
Return | Return | Method Summary | int getLineNumber() Get the current line number. void mark(int readAheadLimit) Mark the present position in the stream. int read() Read a single character. The character read, or -1 if the end of the stream has been reached int read(char[] cbuf, int off, int len) Read characters into a portion of an array. The character read, or -1 if the end of the stream has been reached String readLine() Read a line of text. void reset() Reset the stream to the most recent mark. void setLineNumber(int lineNumber) Set the current line number. long skip(long n) Skip characters.
---|
Revised from Open JDK source code
import java.io.FileReader;
import java.io.LineNumberReader;
public class Main {
public static void main(String[] args) throws Exception {
LineNumberReader lnr = null;
FileReader fr = new FileReader("c:/a.htm");
lnr = new LineNumberReader(fr);
String s;
while ((s = lnr.readLine()) != null)
System.out.println(lnr.getLineNumber() + ": " + s);
}
}