Java 打开文件的选项类似于 Windows c++ FILE_FLAG_WRITE_THROUGH

标签 java c++ java-native-interface

在 C++ 应用程序中打开(或创建)文件时,您可以向操作系统提供提示以满足您的需要。例如,如果您想自定义缓存管理器的行为,您可以在每个文件的基础上禁用写入缓存。

有没有办法在打开带有标志 FILE_FLAG_WRITE_THROUGH 的文件时实现与 c++ 中可能实现的效果相同的效果?

来自:https://msdn.microsoft.com/en-gb/library/windows/desktop/aa363858(v=vs.85).aspx#caching_behavior

A write-through request via FILE_FLAG_WRITE_THROUGH also causes NTFS to flush any metadata changes, such as a time stamp update or a rename operation, that result from processing the request.

我知道 JNI 可以做到这一点,但是因为 POSIX 中有一个类似的选项 (O_DIRECT) 我想知道 java 是否以某种方式支持这种功能。

最佳答案

StandardOpenOption.SYNCStandardOpenOption.DSYNC:

来自Synchronized File I/O Integrity Documentation :

The SYNC and DSYNC options are used when opening a file to require that updates to the file are written synchronously to the underlying storage device. In the case of the default provider, and the file resides on a local storage device, and the seekable channel is connected to a file that was opened with one of these options, then an invocation of the write method is only guaranteed to return when all changes made to the file by that invocation have been written to the device. These options are useful for ensuring that critical information is not lost in the event of a system crash. If the file does not reside on a local device then no such guarantee is made. Whether this guarantee is possible with other provider implementations is provider specific.

Javadoc for SYNC and DSYNC options

在 Linux/MacOS 系统中,这转换为 open 函数的 SYNC/DSYNC 选项 opening files .

在 Windows 中,设置的这些选项中的任何一个都转换为使用 FILE_FLAG_WRITE_THROUGH 选项,可以在源代码中看到 in WindowsChannelFactory :

if (flags.dsync || flags.sync)
        dwFlagsAndAttributes |= FILE_FLAG_WRITE_THROUGH;

要使用这些标志,如果您不熟悉 Java 中的 nio 文件 API,它是这样的:

Path file = Paths.get("myfile.dat");
SeekableByteChannel c = Files.newByteChannel(file, StandardOpenOption.SYNC);

您可以使用字节缓冲区直接使用 channel 来读取/写入数据,或者使用 Channels 转换为熟悉的输入流或输出流类:

InputStream is = Channels.newInputStream(c);    

关于Java 打开文件的选项类似于 Windows c++ FILE_FLAG_WRITE_THROUGH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37295068/

相关文章:

java - java中为什么HashTable存储表中key的hash值

java - spring如何配置CommonsPool2TargetSource?

C++ DLL 不能在不同的机器上运行

java - 在运行时更新 jms 入站适配器目标

java - 如何限制java中哈希集的默认排序

c++ - 我无法在 RAD Studio C++ Builder XE 中构建静态可执行文件

c++ - 如何定义非对称 + 运算符

c++ - 如何在不需要 stdc++ 链接的情况下将 C 程序连接到 C++ 库?

Java JNI : Specify path to dependent shared library

在 native 代码中创建的未命名管道的 Java 输入/输出流?