What exactly is the use of flush for a printwriter

2019-02-24 07:03发布

I'm looking for a theoretical analysis. I mean, how does the buffer system works and what advantage does using flush provide? Kindly illustrate with an example, if possible.

1条回答
Deceive 欺骗
2楼-- · 2019-02-24 07:14

When you are writing to a text file, BufferedWriter does not write it to disk immediately. Instead, it keeps the data in a buffer in memory.

This has the advantage that many small writes will go into the buffer, and then the data will be written to disk in one go, ie. with one big write, instead of many small writes, which would be inefficient.

When the buffer is full, BufferedWriter will write the data out on it's own, ie. it will do the same thing as calling flush() when the buffer is full.

So when should you call flush() manually ?

  • When you need data to be on disk now. If you have a program which reads data from the file on disk at the same time it is written, you may want to ensure all of the data which is supposed to be on disk is actually there.

  • If you are writing through a network connection, you may want to call flush() so that the data gets sent through the network immediately.

Usually it is not necessary to call flush(). Just write and call close() when finished, and no need for flush() as close() flushes the buffer for you.

查看更多
登录 后发表回答