I'm looking at the following example
Which uses the following code
try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
out.write("aString");
out.close();
}
catch (IOException e) {}
What's the advantage over doing
FileWriter fw = new FileWriter("outfilename");
I have tried both and they seem comparable in speed when it comes to the task of appending to a file one line at a time
The Javadoc provides a reasonable discussion on this subject:
In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
If you're writing large blocks of text at once (like entire lines) then you probably won't notice a difference. If you have a lot of code that appends a single character at a time, however, a BufferedWriter
will be much more efficient.
Edit
As per andrew's comment below, the FileWriter
actually uses its own fixed-size 1024 byte buffer. This was confirmed by looking at the source code. The BufferedWriter
sources, on the other hand, show that it uses and 8192 byte buffer size (default), which can be configured by the user to any other desired size. So it seems like the benefits of BufferedWriter
vs. FileWriter
are limited to:
And to further muddy the waters, the Java 6 implementation of OutputStreamWriter
actually delegates to a StreamEncoder, which uses its own buffer with a default size of 8192 bytes. And the StreamEncoder
buffer is user-configurable, although there is no way to access it directly through the enclosing OutputStreamWriter
.
this is explained in the javadocs for outputstreamwriter. a filewriter does have a buffer (in the underlying outputstreamwriter), but the character encoding converter is invoked on each call to write. using an outer buffer avoids calling the converter so often.
http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStreamWriter.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With