In Java, when I call OutputStream.close() do I always need to call OutputStream.flush() before?

前端 未结 4 1109
温柔的废话
温柔的废话 2020-11-27 19:46

If I just call close() in a output stream, the output is guaranteed, or need I call flush() always?

4条回答
  •  情深已故
    2020-11-27 19:46

    If you want the stream to be flushed, then yes, call flush() before calling close().

    Despite all the other answers to the contrary (but as noted correctly in some comments), the default implementation of java.io.OutputStream::close() does not call flush(). In fact, it does nothing. If you have a source distribution, you can easily check it out for yourself, otherwise just trust the official javadoc, quoted here:

    The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.

    The close method of OutputStream does nothing.

    Regardless of whether close() flushes or not, the safest approach should be to flush it manually. If it gets flushed again, who cares?

    The answer by "Tom Hawtin - tackline" has additional details on safely closing streams (but doesn't really answer the original question clearly =P).

提交回复
热议问题