java - Path.toFile() 和 new File(pathString) 的不同行为

标签 java file java-io network-drive java.nio.file

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

我想在 Java 程序中读取该驱动器中的一个文件。

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

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

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

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

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

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

更新

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

最佳答案

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

首先,Path 有不同的实现,正如您提到的,您在 Windows 上工作,所以我查看了我发现的 WindowsPath 的源代码here .

所以 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 的源代码 here .

WindowsPathParser 中的parse 方法是您需要进行调试以查明到底发生了什么的地方。根据您作为方法参数传递的初始 path,此方法将其解析为不同的 WindowsPathType,例如绝对,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]

关于java - Path.toFile() 和 new File(pathString) 的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063113/

相关文章:

java - 更好地理解 Java I/O

java - 使用 https 时 Wicket 不正确的可 Collection 页面 url

java - 将图像添加到 doc 文件

C#:OLE 文件的最大文件名长度

java - System.in.read 实际返回什么?

Java:随机访问文件模式 "rws"与 "rwd"?

java - 如何在 AssertJ 中检查相等或均为空白?

java - 这个 Java HashMap 声明有什么问题?轻松点

java - 如何在Java中将FTPFile列表转换为文件列表?

c - 读取.txt文件并打印结果