flush()java文件处理

问题描述:

flush()的确切用法是什么?流和缓冲区有什么区别?为什么我们需要缓冲区?

What is the exact use of flush()? What is the difference between stream and buffer? Why do we need buffer?

缓冲的优点是效率。通常一次将4096字节的块写入文件比写入一个字节4096次更快。

The advantage of buffering is efficiency. It is generally faster to write a block of 4096 bytes one time to a file than to write, say, one byte 4096 times.

缓冲的缺点是你错过了反馈。对句柄的输出可以保留在内存中,直到写入足够的字节以使其值得写入文件句柄。程序的一部分可能会将一些数据写入文件,但程序的不同部分或其他程序无法访问该数据,直到程序的第一部分将数据从内存复制到磁盘。根据数据写入该文件的速度,这可能需要任意长的时间。

The disadvantage of buffering is that you miss out on the feedback. Output to a handle can remain in memory until enough bytes are written to make it worthwhile to write to the file handle. One part of your program may write some data to a file, but a different part of the program or a different program can't access that data until the first part of your program copies the data from memory to disk. Depending on how quickly data is being written to that file, this can take an arbitrarily long time.

当您调用 flush()$时c $ c>,您要求操作系统立即将缓冲区中的任何数据写入文件句柄,即使缓冲区未满。

When you call flush(), you are asking the OS to immediately write out whatever data is in the buffer to the file handle, even if the buffer is not full.