【问题标题】:Java Path exceptionJava 路径异常
【发布时间】:2017-09-14 13:44:55
【问题描述】:

所以,我之前基本上都使用 java.io.File。 但是现在,当切换到 java.nio.Path 时,我遇到了一些问题......

我使用它基本上是在我的程序启动和关闭时加载/保存文件。

我在多个地方使用它,但我将输入一个示例:

  Objects.requireNonNull(directory, "directory");

    if (this.myObjectMap.isEmpty()) {
        return;
    }

    Files.list(directory).forEach(file -> {
        try {
            Files.deleteIfExists(file);
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    });

    Files.createDirectories(directory);

    for (Object object : this.myObjectMap.values()) {
        Path destination = directory.resolve(object.toString() + ".json");

        Files.deleteIfExists(destination);
        Files.createFile(destination);

        JsonObject properties = new JsonObject();

        JSONFileHandler.save(destination, properties);
    }

我的问题是,每次我做类似的事情时,它甚至在使用路径之前都会抛出 NoSuchFileException 异常......但我不知道我做错了什么,因为我在创建后检查它是否存在路径。

更新

异常堆栈跟踪如下:

java.nio.file.NoSuchFileException: **the directory**

at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsDirectoryStream.<init>(WindowsDirectoryStream.java:86)
at sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream(WindowsFileSystemProvider.java:518)
at java.nio.file.Files.newDirectoryStream(Files.java:457)
at java.nio.file.Files.list(Files.java:3451)

【问题讨论】:

  • 你能发布堆栈跟踪和抛出异常的行吗?
  • 更新了帖子。

标签: java file file-io path


【解决方案1】:

Here'sPath 的 javadoc,它是这么写的:

可用于在文件系统中定位文件的对象。它会 通常表示系统相关的文件路径。

因此,路径只是代表Path,它不是指向现有文件或目录的指针,因此它可能存在也可能不存在。

在我们的示例中,我们需要在调用Files.list 之前检查Path 是否存在,这将确保我们通过有效路径进行迭代,例如:

Path directory = Paths.get("some directory");
Objects.requireNonNull(directory, "directory");
if(Files.exists(directory)){
    Files.list(directory).forEach(file -> {
        try {
            System.out.println(file);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2017-07-26
    • 2017-09-12
    • 2017-10-17
    • 2015-11-09
    相关资源
    最近更新 更多