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.
BufferedOutputStream
?!? This article seems to think otherwise. If that article is true, then althoughFileWriter
andBufferedOutputStream
might be intended for 2 different uses, it is possible (and thus the point of my question) to compare their performance when writing text to a file. – Pommel