Performance: BufferedOutputStream vs FileWriter

I always used FileWriter to write text to a file in Java. Apparently you can also use BufferedOutputStream . Having read both javadocs carefully, I cannot say what was faster / more efficient.

So, I ask: is there a performance difference (even minimal) between these two file I / O methods? If so, what are they and why? If not, why are they virtually the same?

Are there scenarios where one is preferable to the other? Thanks in advance!

+7
java performance file-io disk-io filewriter
source share
2 answers

If you really want to compare FileWriter with BufferedOutputStream to write a text file, the latter should be faster, since there are fewer I / O operations.

  • In the case of FileWriter each call to the write method will be saved immediately (it is not buffered).
  • In the case of a BufferedOutputStream data will be written to disk if the buffer is full (or the buffer is blurred using the flush method).

But if you write text files, you should use Writer ; in this case, we can compare a FileWriter with a BufferedWriter :

Looking at

 FileWriter fw = new FileWriter(...) 

and

 BufferedWriter bw = new BufferedWriter(new FileWriter(...) 

you have the same situation regarding the number of input / output operations.


A FileWriter uses a FileOutputStream internally. The reason for using FileWriter is that it automatically uses the default character encoding when writing to a file (for example, the internal Java string is encoded in UTF-8). If you use OutputStream , you must manually encode in each record:

So this example is for BufferedWriter :

 bw.write("Hello"); 

matches this example for a BufferedOutputStream :

 bos.write("Hello".getBytes(Charset.forName("utf-8"))); 

if your default encoding is utf-8 .

An OutputStream deals with (raw) bytes, while a Writer deals with (text) characters.

+9
source share

A FileWriter writes text to files, and a BufferedOutputStream stores a buffer of arbitrary binary data in memory before writing it to another binary stream that you must provide. They do not do the same, so comparing their performance is pointless.

In general, buffering increases application throughput, but adds latency. In the case of files, you can produce more output per second, because you can transfer large blocks to disk at the same time, so the overhead is one byte lower. On the other hand, when data is buffered in memory, it is not written to disk, so for each specific byte it takes more time to write to disk.

In the case of FileWriter it already has an internal buffer that helps encode characters into bytes. Adding buffering is probably of little value.

+2
source share

All Articles