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

标签 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());
}

一切正常,但如果我输入选项

Files.write(newFile, "Sample text".getBytes(),StandardOpenOption.DELETE_ON_CLOSE);

出现错误

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

所以要工作我必须添加选项

StandardOpenOption.CREATE_NEW

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

我使用的是java版本(build 1.7.0_45-b18)

最佳答案

来自documentation for Files.write :

If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present

因此,一旦您开始指定 OpenOption,您还必须从这三个选项中指定您需要的选项(或者如您已经指出的那样,CREATE_NEW 而不是 创建)。

关于java - 使用 Java 7 使用文件写入不存在的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166618/

相关文章:

Java Scanner.nextDouble()

java - IntelliJ IDEA 中的 "Process finished with exit code 0"是什么意思?

java - 使用java spring boot有什么问题

android - 自动打开 Android 文件的 Intent Chooser

file - 我将如何在 Delphi 中创建一个文本文件

javascript - 在 Nodejs 中解析大型 JSON 文件

Python - Beautifulsoup 到带有图片的 PDF(相对路径)

path - GNU Make 将空格转换为冒号

laravel - 为什么 composer 不在/usr/bin 中全局安装 Laravel?

java - SPRING4 : Failed to read candidate component class CouchbaseConfig. 类