在 C 中,当我调用 open()
打开文件描述符时,我必须显式传递 O_SYNC
标志以确保对此文件的写入将被持久化在 write()
返回时写入磁盘。如果我愿意,我可以不向open()
提供O_SYNC
,然后我的写入将返回得更快,因为它们只需要返回之前将其放入文件系统缓存中。如果我愿意,稍后我可以通过调用 fsync() 强制将此文件的所有未完成写入写入磁盘,该操作会阻塞直到该操作完成。 (有关所有这些的更多详细信息,请参阅 Linux man page。)
有什么方法可以在Java中做到这一点吗?我能找到的最相似的事情是使用 BufferedOutputStream 并在其上调用 .flush() ,但如果我正在写入随机文件偏移量,我相信这意味着输出流的内部缓冲区最终可能会消耗大量内存。
最佳答案
使用 Java 7 NIO FileChannel #force方法:
RandomAccessFile aFile = new RandomAccessFile("file.txt", "rw");
FileChannel inChannel = aFile.getChannel();
// .....................
// flushes all unwritten data from the channel to the disk
channel.force(true);
一个重要的细节:
If the file does not reside on a local device then no such guarantee is made.
关于java - 在没有 O_SYNC 语义的情况下用 Java 编写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35955003/