difference between flush and close function in case of filewriter in java

前端 未结 5 937
傲寒
傲寒 2020-12-04 11:56

I need to know what is exact difference between flush and close function in Java?

And When the data is dumped into a file during writing of file?

Please prov

相关标签:
5条回答
  • 2020-12-04 12:38

    The flush method will flush all the content in the streams to the destination. After writing something, it may not be at the destination.

    The close method will close the streams and will do the flush before closing.

    The following is I got from Oracle Java I/O tutorial.

    To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered.

    If you only use fileWriter without buffer, using flush has no effect. The only thing you need to do is close the streams. And the close method will flush the streams before closing them.

    If I understand correctly, it seems that as long as we remember to close the streams, we are good.

    0 讨论(0)
  • 2020-12-04 12:41

    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. If you want to write some data further, then you have to reopen the stream again and append the data with the existing ones.

    0 讨论(0)
  • 2020-12-04 12:43

    flush() flushes content of buffer to destination.And you can write something again into the stream.close() flushes content to destination and closes the stream. After close() you can't write anything anymore.

    0 讨论(0)
  • 2020-12-04 12:45

    flush() just makes sure that any buffered data is written to disk (in this case - more generally, flushed through whatever IO channel you're using). You can still write to the stream (or writer) afterwards.

    close() flushes the data and indicates that there isn't any more data. It closes any file handles, sockets or whatever. You then can't write to the stream (or writer) any more.

    Note that without calls to flush() data can still be written to the IO channel in question - it's just that some data might be buffered.

    close() generally calls flush() as well, but it's recently been pointed out to me that in some JDK implementations, any exceptions thrown by flushing as part of closing are swallowed :(

    0 讨论(0)
  • 2020-12-04 12:46

    flush() :To flush output stream, use void flush() method of DataOutputStream class. This method internally calls flush() method of underlying OutputStream class which forces any buffered output bytes to be written in the stream.

    close() :It generally close the Stream,connection,socket.

    See flush and close example

    0 讨论(0)
提交回复
热议问题