Buffered Readers and Writers

Input and output can be time-consuming operations. It’s often quicker to read or write text in large chunks rather than in many separate smaller pieces, even when you only process the text in the smaller pieces. The java.io.BufferedReader and java.io.BufferedWriter classes provide internal character buffers. Text that’s written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed. Likewise, reading text from a buffered reader may cause more characters to be read than were requested; the extra characters are stored in an internal buffer. Future reads first access characters from the internal buffer and only access the underlying reader when the buffer is emptied.

Buffering Writes for Better Performance

The java.io.BufferedWriter class is a subclass of java.io.Writer that you chain to another Writer class to buffer characters. This allows more efficient writing of text.

public class BufferedWriter extends Writer

There are two constructors. One has a default buffer size (8192 characters); the other lets you specify the buffer size:

public BufferedWriter(Writer out)
public BufferedWriter(Writer out, int size)

Each time you write to an unbuffered writer, there’s a matching write to the underlying output stream. Therefore, it’s a good idea to wrap a BufferedWriter around each writer whose write() operations are expensive, such as a FileWriter. For example:

BufferedWriter bw = new BufferedWriter(new ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.