Search code examples
javaflushbufferedwriterfile-writing

Is flush() useless for FileWriter since it has no buffer?


When you use the flush() method while using a BufferedWriter, that makes sense because you might want to clear the stream immediately so that the person doesn't have to wait until all the writes are done before the file is updated.

But when you are using a FileWriter, what you put into the parameters of write() is written directly to the file, right?

In this case, there doesn't seem to be a buffer therefore flush is useless (in the case of FileWriter). So is there some kind of mini buffer in the FileWriter that I'm overlooking?


Solution

  • 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).