O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required