java - 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)
两种方法有什么区别吗?它需要任何安全设置吗?
更新
所以在我使用了第二部分(有效的部分)之后,我回到原来的(原样)来验证调试,这一次它有效。我用同一目录中的另一个文件进行了尝试,但失败了。这似乎很奇怪,但我会检查更多。
解决方案
为了更好地了解可能发生的情况,我建议通过代码进行调试。下面我将根据我对源代码的理解来解释可能是什么问题。
首先,有不同的实现,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]
推荐阅读
- hybris - Hybris Backoffice 高级搜索 ReturnRequest 按站点信息搜索
- php - Laravel 中间件未重定向到登录用户的特定路由
- python - Keras 自动编码器错误 - 颗粒状输出
- powershell - ADSI - txt 文件中多台计算机的本地禁用用户列表
- r - 如何将数据(格式yyyy/mm/dd)从csv转换为R(Rstudio)中的向量
- upload - 为动态模块上传 Firebase Crashlytics 本机符号
- react-native - 无法在 FlatList 中呈现对象数组
- sql - 根据标签字段条件过滤查询以列出资源。多对多 SQL 关系表的过滤查询
- c++ - 是否允许 C++ 编译器将最后一次使用的左值隐式转换为右值?
- haskell - 在对象之外更改对象的变量是否被视为副作用?