Using flush() before close()

前端 未结 4 1307
说谎
说谎 2020-11-30 02:34

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 ex

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 02:46

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

提交回复
热议问题