Explanation
But when you are using a FileWriter, what you put into the parameters of write() is written directly to the file, right?
No, the class FileWriter
does use a buffer. So the flush
method has its valid use-case.
If it would have no bufferring, the method would be useless, yes. But it has buffering.
So flush()
must be used to trigger passing the actual data down the stream in case it is still in the internal buffer. Exactly like you already explained, with BufferedWriter
for example.
Documentation and source code
First, the documentation clearly states that it uses buffering-logic (the documentation was updated to highlight this, the old documentation did not mention it that clearly):
Writes text to character files using a default buffer size.
And more details in the parent class:
The resulting bytes are accumulated in a buffer before being written to the underlying output stream.
But okay, let us also take a look at the current implementation (Java 13):
private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192;
// ...
private ByteBuffer bb;
// ...
bb = ByteBuffer.allocate(DEFAULT_BYTE_BUFFER_SIZE);
// bb is used in the write and flush method ...
Note that the implementation is platform specific and can vary between releases, OS and especially different JVMs (the StreamEncoder
is a sun-class).