Java I/O 概念刷新与同步
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4072878/
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
I/O concept flush vs sync
提问by smartnut007
I have come across these two terms and my understanding of them seem to overlap with each other. Flush is used with buffers and sync is used to talk about persisting changes of file to disk.
我遇到过这两个术语,我对它们的理解似乎相互重叠。Flush 与缓冲区一起使用,sync 用于讨论将文件的更改持久化到磁盘。
In C, fflush(stdin) makes sure that the buffer is cleared. And fsync to persist changes file to disk.
在 C 中, fflush(stdin) 确保清除缓冲区。和 fsync 将更改文件持久化到磁盘。
If these concepts are not universally defined, would prefer a linux, java explanation.
如果这些概念没有普遍定义,宁愿有 linux、java 的解释。
I found a related post, but ir doesn't really answer my question. Really force file sync/flush in Java
我找到了一个相关的帖子,但它并没有真正回答我的问题。在 Java 中真正强制文件同步/刷新
采纳答案by Grodriguez
In Java, the flush()
method is used in output streams and writers to ensure that buffered data is written out. However, according to the Javadocs:
在 Java 中,该flush()
方法用于输出流和写入器中,以确保写出缓冲数据。但是,根据 Javadocs:
If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.
如果此流的预期目标是底层操作系统提供的抽象,例如文件,则刷新流仅保证先前写入流的字节会传递给操作系统进行写入;它不保证它们确实被写入物理设备,例如磁盘驱动器。
On the other hand, FileDescriptor.sync()
can be used to ensure that data buffered by the OS is written to the physical device (disk). This is the same as the sync
call in Linux / POSIX.
另一方面,FileDescriptor.sync()
可用于确保操作系统缓冲的数据写入物理设备(磁盘)。这与sync
Linux/POSIX 中的调用相同。
If your Java application really needs to ensure that data is physically written to disk, you may need to flush
and sync
, e.g.:
如果您的 Java 应用程序确实需要确保将数据物理写入磁盘,则可能需要flush
和sync
,例如:
FileOutputStream out = new FileOutputStream(filename);
[...]
out.flush();
out.getFD().sync();
References:
参考: