Java Reference
In-Depth Information
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 immedi-
ately 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");
}
}
 
Search WWH ::




Custom Search