带有 StandardOpenOption.CREATE 的 Files.newInputStream 中的 NoSuchFileException

Ara*_*oft 6 java nio

如果文件不存在,我正在尝试打开文件进行读取或创建文件。我使用这个代码:

String location = "/test1/test2/test3/";
new File(location).mkdirs();
location += "fileName.properties";
Path confDir = Paths.get(location);
InputStream in = Files.newInputStream(confDir, StandardOpenOption.CREATE);
in.close();
Run Code Online (Sandbox Code Playgroud)

我得到 java.nio.file.NoSuchFileException

考虑到我正在使用StandardOpenOption.CREATE选项,如果文件不存在,则应创建该文件。

知道为什么我会收到此异常吗?

Kli*_*cou 2

看来您希望发生两件完全不同的事情之一:

  1. 如果文件存在,则读取;或者
  2. 如果该文件不存在,则创建它。

这两件事是相互排斥的,但你似乎混淆了它们。如果该文件不存在并且您刚刚创建它,则读取它是没有意义的。因此,将两件事分开:

    Path confDir = Paths.get("/test1/test2/test3");
    Files.createDirectories(confDir);
    Path confFile = confDir.resolve("filename.properties");

    if (Files.exists(confFile))
        try (InputStream in = Files.newInputStream(confFile)) {
            // Use the InputStream...
        }
    else
        Files.createFile(confFile);
Run Code Online (Sandbox Code Playgroud)

还要注意,最好使用“try-with-resources”而不是手动关闭InputStream。