Benefits of using flush() close() in Android streams?

Warpzit picture Warpzit · Nov 18, 2011 · Viewed 12.7k times · Source

I know the general idea but I'm just not sure if it has an effect since the Android api states following: "Flushes this stream. Implementations of this method should ensure that any buffered data is written out. This implementation does nothing."

This implementation does nothing <-- does that mean its useless to do or am I missing something?

Answer

Marek Sebera picture Marek Sebera · Nov 18, 2011

If you read extended docs on oracle

http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.html#flush()

Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The flush method of OutputStream does nothing.

Means, the method itself does nothing, and it is abstract, so any underlying Class can implement its own version of flushing streams and forcing them to write (not waiting in write queue)

But anyway, as Guillaume pointed out, it's good practice to call it anyway. If later on, you replace your stream with another implementation that does use it, then you'll be sorry.

Depending on the OS, flush() does nothing more than force the data to be written to the OS.

and

flush() does nothing on FileOutputStream. It is only useful on buffered streams.

and from javadoc of close(), just to note you don't have to flush stream if you're closing it immediately after.

Close the stream, flushing it first. Once a stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously-closed stream, however, has no effect.

related:
FileOutputStream.close is really slow when writing large file
flush in java.io.FileWriter