打印器对象的flush到底有什么用? [英] What exactly is the use of flush for a printwriter object?

查看:16
本文介绍了打印器对象的flush到底有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找理论分析.我的意思是,缓冲系统是如何工作的,使用flush 有什么好处?如果可能,请举例说明.

解决方案

当您写入文本文件时,BufferedWriter 不会立即将其写入磁盘.相反,它将数据保存在内存中的缓冲区中.

这样做的好处是,很多小的写入都会进入缓冲区,然后数据会一次写入磁盘,即.一次大写,而不是许多小写,这将是低效的.

当缓冲区已满时,BufferedWriter 将自己写出数据,即.当缓冲区已满时,它会执行与调用 flush() 相同的事情.

那么你什么时候应该手动调用flush()?

  • 当您需要现在将数据存储在磁盘上时.如果您有一个程序在写入磁盘上的文件的同时读取数据,您可能需要确保所有应该在磁盘上的数据实际上 那里.

  • 如果您通过网络连接写入,您可能需要调用 flush() 以便数据立即通过网络发送.

通常没有需要调用flush().完成后只需编写并调用 close(),无需 flush(),因为 close() 会为您刷新缓冲区.>

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.

解决方案

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.

这篇关于打印器对象的flush到底有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆