Last Updated on 28 July 2019   |   Print Email
In Java File I/O programming, the classes BufferedReader and LineNumberReader allows reading a sequence of lines from a text file, in a line-by-line fashion, by using their readLine() method. The LineNumberReader is a subclass of the BufferedReader class. The only difference is that, the LineNumberReader class keeps track of the current line number, whereas the BufferedReader class does not.Reading all lines from a text file using the BufferedReader class is as easy as follows:
The above code snippet takes a given text file, reads every line and prints content of each line to the console output. It’s also common to read and put all the lines into a collection (e.g. an array list) for processing later, like this:
BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
List<String> listLines = new ArrayList<String>();
while ((lineText = lineReader.readLine()) != null) {
listLines.add(lineText);
}
lineReader.close();
Using the LineNumberReader class is similar to the BufferedReader class, for example:
The LineNumberReader class provides the getLineNumber() method which returns the current line number, so we can use it for checking conditions on line numbers, for example:
Printing only the even lines:
while ((lineText = lineReader.readLine()) != null) {
int lineNumber = lineReader.getLineNumber();
if (lineNumber % 2 == 0) {
System.out.println(lineNumber + ": " + lineText);
}
}
Printing only the lines in a specific range:
while ((lineText = lineReader.readLine()) != null) {
int lineNumber = lineReader.getLineNumber();
if (lineNumber >= 50 && lineNumber <= 100) {
System.out.println(lineNumber + ": " + lineText);
}
}
NOTES:The LineNumberReader class also provides the setLineNumber() method but it doesn’t change to the current position in the file stream. It only changes the value that will be returned by the getLineNumber() method.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments
pls provide
getline num set line num examples