您好,我尝试写入不存在的文件
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
, andWRITE
options are present
因此,一旦您开始指定 OpenOption
,您还必须从这三个选项中指定您需要的选项(或者如您已经指出的那样,CREATE_NEW
而不是 创建
)。
关于java - 使用 Java 7 使用文件写入不存在的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166618/