2

The api of FileWriter begins with these words:

"Writes text to character files using a default buffer size."

The api of BufferedWriter begins with these words:

"Writes text to a character-output stream, buffering characters [...]"

So, obviously both classes are using buffers. Unfortunately, the api does not explain the differences between those two kinds of buffers.

So, I am asking myself: Where is the difference?

mrbela
  • 4,477
  • 9
  • 44
  • 79

2 Answers2

0

BufferedWriter is more efficient when you have multiple writes. It saves up small writes and writes in one large chunk. Below is the write() method of BufferedWriter which checks if the buffer is full if (nextChar >= nChars) and flushes the buffer.

public void write(int c) throws IOException {
    synchronized (lock) {
        ensureOpen();
        if (nextChar >= nChars)
            flushBuffer();
        cb[nextChar++] = (char) c;
    }
}

as for FileWriter, every write is making one system call unlike BufferedWriter which makes a system after the buffer is full. So if you have multiple small writes, BufferedWriter would be more efficient.

mkjh
  • 1,634
  • 13
  • 25
0

BufferedWriter has a better buffer writing implementation than FileWriter, performance wise

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")));

For buffering FileWriter is extending OutputStreamWriter which points to using BufferedWriter as well

For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations.

Community
  • 1
  • 1
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Frankly, I think the documentation actually contradicts the source. The source of `OutputStreamWriter` includes a character buffer and converts only when it is full. – RealSkeptic Jan 14 '19 at 13:53
  • @RealSkeptic in the implementation, I’ve looked up, it only features a byte buffer holding the encoded content. Still, it will reduce the number of actual I/O operations and having another character buffer on the writer’s side won’t improve that. Regarding the documentation, the assumption that “to avoid frequent converter invocations” will lead to “top efficiency” is flawed in general, like almost every statement about buffering in the `java.io` package. That has a long tradition. – Holger Jan 22 '19 at 12:58