Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what is the advantage of using BufferedWriter to append to a file?

Tags:

java

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

like image 735
deltanovember Avatar asked Aug 08 '11 00:08

deltanovember


2 Answers

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:

  • Larger default buffer size.
  • Ability to override/customize the buffer size.

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.

like image 195
aroth Avatar answered Oct 10 '22 20:10

aroth


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

like image 34
andrew cooke Avatar answered Oct 10 '22 18:10

andrew cooke