What exactly is the use of flush for a printwriter object?

ε祈祈猫儿з 提交于 2019-11-29 14:40:18

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!