使用 Java 7 使用 Files 写入不存在的文件

Xel*_*ian 4 java file path java-7

嗨,我尝试写入不存在的文件

public static void main(String[] args) throws IOException {
        Path newFile = Paths.get("output.txt");
        Files.write(newFile, "Sample text".getBytes());
}
Run Code Online (Sandbox Code Playgroud)

一切都好,但如果我把选项

Files.write(newFile, "Sample text".getBytes(),StandardOpenOption.DELETE_ON_CLOSE);
Run Code Online (Sandbox Code Playgroud)

出现错误

Exception in thread "main" java.nio.file.NoSuchFileException: problem.txt
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
Run Code Online (Sandbox Code Playgroud)

所以为了工作,我必须添加选项

StandardOpenOption.CREATE_NEW
Run Code Online (Sandbox Code Playgroud)

为什么在第二次尝试StandardOpenOption.DELETE_ON_CLOSE中不起作用,但第一次没有任何选项可以工作并创建文件?

我正在使用 java 版本(构建 1.7.0_45-b18)

Pow*_*ord 5

文档中Files.write

如果不存在任何选项,则此方法的工作原理就好像CREATETRUNCATE_EXISTINGWRITE选项都存在

因此,一旦您开始指定OpenOptions,您还必须从这三个中指定您需要的选项(或者您已经注意到,CREATE_NEW而不是CREATE)。