简体   繁体   English

flush()Java文件处理

[英]flush() java file handling

What is the exact use of flush()? flush()的确切用途是什么? What is the difference between stream and buffer? 流和缓冲区有什么区别? Why do we need buffer? 为什么需要缓冲?

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. 通常,一次将4096字节的块写入文件要比写入4096字节的速度快。

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. 根据将数据写入该文件的速度,此过程可能会花费任意长时间。

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. 调用flush() ,您要求操作系统立即将缓冲区中的任何数据写到文件句柄中,即使缓冲区未满。

有时,在实际将数据写入磁盘之前(在缓冲区中),数据会被缓存,刷新会导致将缓冲区中的内容写入磁盘。

flush tells an output stream to send all the data to the underlying stream. flush告诉输出流将所有数据发送到基础流。 It's necessary because of internal buffering. 由于内部缓冲,这是必需的。 The essential purpose of a buffer is to minimize calls to the underlying stream's APIs. 缓冲区的基本目的是最大程度地减少对基础流的API的调用。 If I'm storing a long byte array to a FileOutputStream , I don't want Java to call the operating system file API once per byte. 如果我将一个长字节数组存储到FileOutputStream ,则我不希望Java每个字节调用一次操作系统文件API。 Thus, buffers are used at various stages, both inside and outside Java. 因此,在Java内部和外部的各个阶段都使用缓冲区。 Even if you did call fputc once per byte, the OS wouldn't really write to disk each time, because it has its own buffering. 即使您每个字节调用一次fputc ,操作系统也不会每次都真正写入磁盘,因为它具有自己的缓冲。

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

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