If I just call close()
in a output stream, the output is guaranteed, or need I call flush()
always?
Close an OutputStreamOnce you are done writing data to a Java OutputStream you should close it.
Java OutputStream flush() Method The flush() method of OutputStream class is used to flush the content of the buffer to the output stream. A buffer is a portion in memory that is used to store a stream of data(characters). That data sometimes will only get sent to an output device, when the buffer is full.
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.
Its close() method does NOT call flush() .
Whilst close
should call flush
, it's a bit more complicated than that...
Firstly, decorators (such as BufferedOutputStream
) are common in Java. Construction of the decorator may fail, so you need to close
the "raw" stream in a finally
block whose try
includes the decorator. In the case of an exception, you don't usually need to close
the decorator (except, for instance, for badly implemented compression decorators). You do typically need to flush
the decorator in the non-exception case. Therefore:
final RawOutputStream rawOut = new RawOutputStream(rawThing); try { final DecoratedOutputStream out = new DecoratedOutputStream(rawOut); // ... stuff with out within ... out.flush(); } finally { rawOut.close(); }
To top it, decorator close
methods are often implemented incorrectly. That includes some in java.io
until recently.
Of course, you probably want to use the Execute Around idiom to keep in DRY(ish).
Edit: Since Java 8 you can use try-with-resource statements that should handle everything nicely and concisely. The code will call close on each resource even if unnecessary.
try ( RawOutputStream rawOut = new RawOutputStream(rawThing); DecoratedOutputStream out = new DecoratedOutputStream(rawOut) ) { // ... stuff with out within ... }
Close() always flushes so no need to call.
EDIT: This answer is based on common sense and all the outputstream I encountered. Who is going to implement a close() for a buffered stream without flushing buffer first? There is no harm to call flush right before close(). However, there are consequences if flush() is called excessively. It may defeat underneath buffering mechanism.
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