开发者

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

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:

  • 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.


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


A buffer effectivity is more easily seen when the load is high. Loop the out.write a couple thousand of times and you should see a difference.

For a few bytes passed in just one call probably the BufferedWriter is even worse (because it problably later calls FileOutputStream).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜