问题
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()?
回答1:
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.
回答2:
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.
回答3:
I want to point out an important concept that many previous comments have alluded to:
A stream's close()
method does NOT necessarily invoke flush()
.
For example org.apache.axis.utils.ByteArray#close() does not invoke flush()
.
(click link to see source code)
The same is true more generally for any implementations of Flushable
and Closeable
. A prominent example being java.io.PrintWriter. Its close()
method does NOT call flush()
.
(click link to see source code)
This might explain why developers are cautiously calling flush()
before closing their streams. I personally have encountered production bugs in which close()
was called on a PrintWriter instance without first calling flush()
.
来源:https://stackoverflow.com/questions/9858495/using-flush-before-close