Reading a line at a time
On the previous page we introduced the InputStreamReader
used to read successive characters from a character stream, and mentioned that it was usual to wrap the latter reader in a BufferedReader. The BufferedReader class also provides an additional facility: to read a line at a time from the character stream.
To read the next line from the stream, call BufferedReader.readLine().
A benefit of this method is that it will cope with both UNIX and Windows-style
line breaks1. So here is a method to count the number of lines in an ASCII text file:
public int countASCIILines(File f) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(f), "US-ASCII"));
try {
int count = 0;
String line;
while ((line = br.readLine()) != null) {
count++;
}
return count;
} finally {
br.close();
}
}
Notice that the readLine() method signals an end of file
by returning null.
1. You've probably come across this particularly if you're a Windows user. You may have tried loading certain text files into notepad only to find that the entire file is displayed on a single line. This is because the UNIX convention is to denote line breaks by a single ASCII 10 ("newline") character, whereis in Windows the convention is still to use a character 13 ("carraige return") followed by a newline character, harking back to the days of teletype printers.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.