As per the java docs, invoking close() on any java.io Streams automatically invokes flush(). But I have seen in lot of examples, even in production codes, developers have explicitly used flush() just before close(). In what conditions we need to use flush() just before close()?
Its close() method does NOT call flush() .
flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream. But close() closes the stream permanently.
When you write data to a stream, it is not written immediately, and it is buffered. So use flush() when you need to be sure that all your data from buffer is written. We need to be sure that all the writes are completed before we close the stream, and that is why flush() is called in file/buffered writer's close() .
flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it.
Developer get into a habit of calling flush() after writing something which must be sent.
IMHO Using flush() then close() is common when there has just been a write e.g.
// write a message out.write(buffer, 0, size); out.flush(); // finished out.close();
As you can see the flush() is redundant, but means you are following a pattern.
I guess in many cases it's because they don't know close()
also invokes flush()
, so they want to be safe.
Anyway, using a buffered stream should make manual flushing almost redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With