Search code examples
javaperformancefile-iofilewriterdisk-io

Performance: BufferedOutputStream vs FileWriter


I've always used a FileWriter to write text to a file in Java. Apparently you can also use a BufferedOutputStream as well. After reading both javadocs carefully, I can't seem to tell which was is faster/more efficient.

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

Are there scenarios where one is preferred over the other? Thanks in advance!


Solution

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

    • In the case of FileWriter, each call to a write method will be persisted at once (it's unbuffered).
    • In the case of a BufferedOutputStream, data will be written to disk, if the buffer is full (or the buffer is flushed explicity using the flush method).

    But if you write text files, you should use a 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 I/O operations.


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

    So this example for a BufferedWriter:

    bw.write("Hello");
    

    corresponds to that 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 whereas a Writer deals with (text) characters.