'FileWriter vs BufferedWriter

I would like to know whether or not FileWriter is buffered.

In this SO question, it seems that it is, however in this SO question it seems that is not.(it would be a system call for each time write(..) gets called.

So basically reading those two Q&A I am a little confused. Is anybody able to clearly explain it out?

Thanks in advance.

EDIT: Problem solved by reading this API of which I am quoting the relevant part:

Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.

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

Writer out = new BufferedWriter(new OutputStreamWriter(System.out));

Since FileWriter extends OutputStreamWriter, it applies to it as well.

Thanks for your time though, I am aware I asked something quite specific.



Solution 1:[1]

I would recomand to always use a BufferedWriter. It allows you to control the actual buffer size and you can guarantee that regardless of the JVM you use, IO will be buffered which brings a huge IO performance boost.

Solution 2:[2]

In fact, a FileWriter does have internal buffering. The buffer is a ByteBuffer (with default size 8192 bytes). You can find it in the sun.io.cs.StreamEncoder object that OutputStreamWriter uses to encode characters to the chosen character set / encoding.

I looked at the Java 17 OpenJDK source code to determine this. It is an implementation detail, and could vary depending on Java version ... and vendor.

Solution 3:[3]

FileWriter is not buffered, you have to use a BufferedWriter as a wrapper:

final int myBufferSize = 2048;

Writer myWriter = new BufferedWriter(new FileWriter, myBufferSize);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 morpheus05
Solution 2 Stephen C
Solution 3 pocoLoco