Javadoc gives a reasonable discussion on this:
In general, Writer immediately sends its output to the underlying character or byte stream. If a request is not required, we recommend wrapping the BufferedWriter around any Writer whose write () operations can be expensive, such as FileWriters and OutputStreamWriters. For example,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer PrintWriter output to a file. Without buffering, each call to the print () method causes the characters to be converted to bytes, which will then be written immediately to a file, which can be very inefficient.
If you write large blocks of text at once (for example, whole lines), you probably won't notice the difference. However, if you have a lot of code that adds one character at a time, then BufferedWriter will be much more efficient.
Edit
According to the comment below, FileWriter actually uses its own 1024-byte fixed-size buffer. This was confirmed by viewing the source code. BufferedWriter sources , on the other hand, show that it uses a buffer size of 8192 bytes (the default), which can be configured by the user to any other desired size. Thus, the benefits of BufferedWriter vs. FileWriter limited:
- The default maximum buffer size.
- Ability to override / adjust buffer size.
And for further troubled waters, the implementation of Java 6 OutputStreamWriter actually delegates to StreamEncoder , which uses its own buffer with a default size of 8192 bytes. The StreamEncoder buffer is StreamEncoder configurable, although access to it is not possible directly through OutputStreamWriter .
aroth
source share