Readers Writers  «Prev  Next»


Lesson 5Buffering reads for better performance
ObjectiveWrite a program that reads a text file line by line

Buffering reads better Performance (Java)

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. BufferedReader is also notable for its readLine() method, which allows you to read text a line at a time. This replaces the deprecated readLine() method in DataInputStream.
Each time you read from an unbuffered Reader, there's a matching read from the underlying input stream. Therefore it is a good idea to wrap a BufferedReader around each reader whose read() operations are expensive, such as a FileReader.
See example below.

Using BufferedReader

Here is an example of using BufferedReader:
BufferedReader br =
new BufferedReader(new FileReader("37.html"));

Constructors


There are two constructors, one with a default buffer size of 8,192 characters, and one that lets you specify the buffer size.
public BufferedReader(Reader in, int buffer_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. The characters \r, \n, and \r\n are assumed to be line breaks and are not included in the returned string.
The readLine() method is often used when reading user input from System.in, since most platforms only send the user's input to the running program after the user has typed a full line (that is, when the user presses the Return or Enter key).

Marking and resetting

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

Buffering Reads-for better Performance-Exercise

Click the Exercise link below to write a program that uses a BufferedReader and readLine() to read all files named on the command line, line by line, and then copy them to System.out.
Buffering Reads-for better Performance-Exercise