使用 nio 创建文件时出现 NoSuchFileException

NoSuchFileException when creating a file using nio

我正在尝试使用 java nio 创建一个新文件,但我 运行 遇到了 createFile 错误。错误如下所示:

 createFile error: java.nio.file.NoSuchFileException: /Users/jchang/result_apache_log_parser_2015/06/09_10:53:49

代码段如下所示:

 String filename = "/Users/jchang/result_apache_log_parser_" + filename_date;
        Path file = Paths.get(filename);
        try {
            Files.createFile(file);
        } catch (FileAlreadyExistsException x) {
            System.err.format("file named %s" +
                    " already exists%n", file);
        } catch (IOException x) {
            System.err.format("createFile error: %s%n", x);
        }

有人知道如何解决这个问题吗?感谢您的帮助!

我会说 Turing85 是正确的。您的 filename_date 变量中有斜杠。所以 /Users/jchang/result_apache_log_parser_2015 必须作为一个目录存在。这就是 NoSuchFileException 目录丢失的原因。

您的代码至少有两个问题。首先:您的文件名中有路径分隔符 (/)。第二:至少在 Windows 下,您的解决方案在 filname (:).

中包含非法字符

要解决第一个问题,您可以走两条路:a) 创建您需要的所有文件夹或 b) 将分隔符更改为不同的内容。我会解释两者。

要将所有文件夹创建到一个路径,您只需调用

Files.createDirectories(path.getParent());

其中 path 是一个文件(重要!)。通过在文件上调用 getParent(),我们得到 path 所在的文件夹。 Files.createDirectories(...) 负责剩下的事情。

b) 更改分隔符:没有比这更容易的了:

String filename =  "/Users/jchang/result_apache_log_parser_"
                 + filename_date.replace("/", "_")
                                .replace(":", "_");

这应该会产生类似 /User/jchang/result_apache_parser_2015_06_09_10_53_29

的结果

对于 b) 我们也解决了第二个问题。

现在让我们一起设置并应用 nio:

的一些小技巧
String filename =  "/Users/jchang/result_apache_log_parser_"
                 + filename_date.replace('/', '_')
                                .replace(':', '_');

Path file = Paths.get(filename);
try {
    // Create sub-directories, if needed.
    Files.createDirectories(file.getParent());
    // Create the file content.
    byte[] fileContent = ...;
    // We do not need to create the file manually, let NIO handle it.
    Files.write(file
                , fileContent
                // Request permission to write the file
                , StandardOpenOption.WRITE
                // If the file exists, append new content
                , StandardOpenOption.APPEND
                // If the file does not exist, create it
                , StandardOpenOption.CREATE);
} catch (IOException e) {
    e.printStackTrace();
}

有关 nio 的详细信息,请单击 here

正如许多人所说,您需要创建中间目录,例如 ../06/..

所以使用这个,在创建文件之前创建不存在的目录,

Files.createDirectories(mPath.getParent());

所以你的代码应该是:

    Path file = Paths.get(filename);
    try {
        Files.createDirectories(file.getParent());
        Files.createFile(file);
    } catch (FileAlreadyExistsException x) {
        System.err.format("file named %s" +
                " already exists%n", file);
    } catch (IOException x) {
        System.err.format("createFile error: %s%n", x);
    }