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 sz)
  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) { // while loop begins here
         System.out.println(thisLine);
       } // end while 
     } // end try
     catch (IOException e) {
       System.err.println("Error: " + e);
     }
  } // end for
  
} // end main

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

 public boolean markSupported()
 public void mark(int readAheadLimit) throws IOException
 public void reset() throws IOException
Finally, BufferedReader overrides several methods from the superclass Reader; but how you use them does not change at all:

 public int read() throws IOException
 public int read(char c[], int off, int length) throws IOException
 public long skip(long n) throws IOException
 public boolean ready() throws IOException
 public void close() throws IOException

Previous | Next | Top
Last Modified June 16, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu