20.5.9. LineNumberReader
The LineNumberReader stream keeps track of line numbers while reading text. As usual a line is
considered to be terminated by any one of a line feed (\n), a carriage return (\r), or a carriage return
followed immediately by a linefeed (\r\n).
The following program prints the line number where the first instance of a particular character is found in a
file:
import java.io.*;
class FindChar {
public static void main(String[] args)
throws IOException
{
if (args.length != 2)
throw new IllegalArgumentException(
"need char and file");
int match = args[0].charAt(0);
FileReader fileIn = new FileReader(args[1]);
LineNumberReader in = new LineNumberReader(fileIn);
int ch;
while ((ch = in.read()) != -1) {
if (ch == match) {
System.out.println("'" + (char)ch +
"' at line " + in.getLineNumber());
return;
}
}
System.out.println((char)match + " not found");
}
}
This program creates a FileReader named fileIn to read from the named file and then inserts a
LineNumberReader, named in, before it. LineNumberReader objects get their characters from the
reader they are attached to, keeping track of line numbers as they read. The getLineNumber method
returns the current line number; by default, lines are counted starting from zero. When this program is run on
itself looking for the letter 'I', its output is
'I' at line 4
You can set the current line number with setLineNumber. This could be useful, for example, if you have a
file that contains several sections of information. You could use setLineNumber to reset the line number
to 1 at the start of each section so that problems would be reported to the user based on the line numbers
within the section instead of within the file.
LineNumberReader is a BufferedReader that has two constructors: One takes a reference to the
wrapped stream and the size of the buffer to use, while the other only takes a reference to the wrapped stream
and uses a default buffer size.
Exercise 20.5: Write a program that reads a specified file and searches for a specified word, printing each line
number and line in which the word is found.