Search this site

 Home  I/O  Buffering  Character streams  NIO intro  Buffers  Channels  Buffer performance

Search this site:
Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java

 What do you think of this article? Did it help you? Found a mistake? Feedback and suggestions here

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.

comments powered by Disqus

Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved.