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.

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 and that does not require immediate response, such as a FileWriter. For example,

 BufferedWriter bw = new BufferedWriter(new FileWriter("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 BufferedWriter(Writer out)
 public BufferedWriter(Writer out, int size)
The one new method in this class is newLine(). This method that writes a platform dependent line terminator string, \n on Unix, \r on the Mac, \r\n on Windows.

 public String newLine() throws IOException
Finally, BufferedWriter overrides several methods from the superclass Writer; but how you use them does not change at all:

 public void write(int c) throws IOException
 public void write(char c[], int off, int length) throws IOException
 public void write(String s, int offset, int length) throws IOException
 public void flush() throws IOException
 public void close() throws IOException
 

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