首页 > 解决方案 > Path.toFile() 和 new File(pathString) 的不同行为

问题描述

我在 Windows 中安装了一个网络驱动器(samba 服务器)。

我在那个驱动器中有一个文件,我想在 Java 程序中读取它。

在我尝试使用以下方法读取文件之前:

Paths.get(basePath, fileName).toFile()

但是由于文件不存在的错误而失败。文件在那里,路径很好。

然后我尝试了以下有效的代码:

String path = Paths.get(basePath, fileName).toAbsolutePath().toString()
File file = new File(path)

两种方法有什么区别吗?它需要任何安全设置吗?

更新

所以在我使用了第二部分(有效的部分)之后,我回到原来的(原样)来验证调试,这一次它有效。我用同一目录中的另一个文件进行了尝试,但失败了。这似乎很奇怪,但我会检查更多。

标签: javafilejava-ionetwork-drivejava.nio.file

解决方案


为了更好地了解可能发生的情况,我建议通过代码进行调试。下面我将根据我对源代码的理解来解释可能是什么问题。

首先,有不同的实现,Path正如你提到的,你在 Windows 上工作,所以我查看了WindowsPath我在这里找到的源代码。

所以方法Path.toFile()很简单。这是:

public final File toFile() {
    return new File(this.toString());
}

this指的是 Path 实现的实例,在 Windows 的情况下,它是WindowsPath.

查看WindowsPath我们看到的类toString()实现如下:

@Override
public String toString() {
    return path;
}

现在看看这个path变量是如何构建的。该类WindowsPath调用WindowsPathParser构建路径的类。WindowsPathParser可以在这里找到源代码。

中的parse方法WindowsPathParser是您需要调试以确切了解发生了什么的地方。根据您path作为方法参数传递的初始值,此方法将其解析为不同的参数,WindowsPathType例如 ABSOLUTE、DIRECTORY_RELATIVE。

下面的代码显示了初始path输入如何改变WindowsPathType

代码

private static final String OUTPUT = "Path to [%s] is [%s]";

public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
    printPathInformation("c:\\dev\\code");
    printPathInformation("\\c\\dev\\code");
}

private static void printPathInformation(String path) throws NoSuchFieldException, IllegalAccessException {
    Path windowsPath = Paths.get(path);

    Object type = getWindowsPathType(windowsPath);

    System.out.println(String.format(OUTPUT,path, type));
}

private static Object getWindowsPathType(Path path) throws NoSuchFieldException, IllegalAccessException {
    Field type = path.getClass().getDeclaredField("type");

    type.setAccessible(true);

    return type.get(path);
}

输出

Path to [c:\dev\code] is [ABSOLUTE]
Path to [\c\dev\code] is [DIRECTORY_RELATIVE]

推荐阅读