简体   繁体   English

对于printwriter对象,flush的用途是什么?

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

I'm looking for a theoretical analysis. 我正在寻找理论分析。 I mean, how does the buffer system works and what advantage does using flush provide? 我的意思是,缓冲系统如何工作以及使用flush提供什么优势? Kindly illustrate with an example, if possible. 如果可能的话,请举例说明。

When you are writing to a text file, BufferedWriter does not write it to disk immediately. 当您写入文本文件时, BufferedWriter不会立即将其写入磁盘。 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. 当缓冲区已满时, BufferedWriter将自己写出数据,即。 it will do the same thing as calling flush() when the buffer is full. 当缓冲区已满时,它将执行与调用flush()相同的操作。

So when should you call flush() manually ? 那么什么时候应该手动调用flush()

  • 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. 如果您是通过网络连接进行编写,则可能需要调用flush()以便立即通过网络发送数据。

Usually it is not necessary to call flush() . 通常没有必要调用flush() Just write and call close() when finished, and no need for flush() as close() flushes the buffer for you. 只需在完成时编写并调用close() ,并且不需要flush()作为close()为您刷新缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM