java flush() java文件处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4040221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:29:18  来源:igfitidea点击:

flush() java file handling

javafile-handling

提问by Sumithra

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

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

回答by socket puppet

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

回答by Tom

The data sometimes gets cached before it's actually written to disk (in a buffer) flush causes what's in the buffer to be written to disk.

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

回答by Matthew Flaschen

flushtells an output stream to send all the data to the underlying stream. It's necessary because of internal buffering. The essential purpose of a buffer is to minimize calls to the underlying stream's APIs. 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. Thus, buffers are used at various stages, both inside and outside Java. Even if you did call fputconce per byte, the OS wouldn't really write to disk each time, because it has its own buffering.

flush告诉输出流将所有数据发送到底层流。由于内部缓冲,这是必要的。缓冲区的基本目的是最小化对底层流 API 的调用。如果我将一个长字节数组存储到 a FileOutputStream,我不希望 Java 每个字节调用一次操作系统文件 API。因此,缓冲区用于 Java 内部和外部的各个阶段。即使您确实fputc每个字节调用一次,操作系统也不会每次都真正写入磁盘,因为它有自己的缓冲。