Buffering Reads for Better Performance

The java.io.BufferedReader class is a subclass of java.io.Reader that you chain to another Reader class to buffer characters. This allows more efficient reading of characters and lines.

The BufferedReader is also notable for its readLine() method that allows you to read text a line at a time.

Each time you read from an unbuffered Reader, there's a matching read from the underlying input stream. Therefore it's a good idea to wrap a BufferedReader around each Reader whose read() operations are expensive, such as a FileReader. For example,

BufferedReader br = new BufferedReader(new FileReader("37.html"));

There are two constructors, one with a default buffer size of 8192 characters, and one that lets you specify the buffer size:

  public BufferedReader(Reader in, int size)
  public BufferedReader(Reader in)

The one new method in this class is readLine().

 public String readLine() throws IOException

This method returns a String that contains a line of text from a text file. \r, \n, and \r\n are assumed to be line breaks and are not included in the returned String. The following example reads a text file, line by line, and prints it to System.out:

// Implement the Unix cat utility in Java

import java.io.*;

class Cat  {

  public static void main (String args[]) {
  
    String thisLine;
 
   //Loop across the arguments
   for (int i=0; i < args.length; i++) {
 
     //Open the file for reading
     try {
       BufferedReader br = new BufferedReader(new FileReader(args[i]));
       while ((thisLine = br.readLine()) != null) {
         System.out.println(thisLine);
       } // end while 
     } // end try
     catch (IOException ex) {
       System.err.println("Error: " + ex.getMessage());
     }
  } // end for
  
} // end main

}

BufferedReaders do support marking and resetting, at least up to the length of the buffer.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified August 22, 2006