Readers Writers  «Prev  Next»


Lesson 4Buffering writes for better performance
ObjectiveExamine how to increase text-writing efficiency with buffering.

Buffering writes (increase text-writing efficiency)

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. 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 that has expensive write() operations and that does not require immediate response, such as a FileWriter.

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 BufferedWriter(Writer out)

public BufferedWriter(Writer out, int size)
Here's an example of using BufferedWriter:
BufferedWriter bw = new BufferedWriter(new FileWriter("37.html"));

The newLine( ) method

The one new method in this class is newLine(). This method writes a platform-dependent line terminator string, \n on Unix, \r on the Mac, \r\n on Windows.
public String newLine() throws IOException