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

I look at example

What uses the following code

try { BufferedWriter out = new BufferedWriter(new FileWriter("outfilename")); out.write("aString"); out.close(); } catch (IOException e) {} 

What an advantage before doing

 FileWriter fw = new FileWriter("outfilename"); 

I tried both and they seem to be comparable in speed when it comes to adding a file one line at a time

+7
source share
3 answers

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 .

+12
source

this is explained in javadocs for outputstreamwriter. the file has a buffer (in the base outputstreamwriter), but the character encoding converter is called for each call to be written. the use of an external buffer avoids frequent calls to the converter.

http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStreamWriter.html

+3
source

Buffer efficiency is easier to see when the load is high. Run out.write a couple of thousand times and you should see the difference.

For a few bytes transferred with just one call, probably BufferedWriter is even worse (because it probably calls FileOutputStream later).

+1
source

All Articles