我正在尝试理解Java在创建File
对象时如何解析相对路径。
使用的操作系统:Windows
对于以下代码片段,我遇到了IOException
,因为它找不到该路径:
@Test
public void testPathConversion() {
File f = new File("test/test.txt");
try {
f.createNewFile();
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
} catch (Exception e) {
e.printStackTrace();
}
}
我的理解是,Java把提供的路径作为绝对路径处理,如果路径不存在,则返回错误,这是有道理的。
当我更新上面的代码以使用相对路径时:
@Test
public void testPathConversion() {
File f = new File("test/../test.txt");
try {
f.createNewFile();
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
} catch (Exception e) {
e.printStackTrace();
}
}
它创建一个新文件并提供以下输出:
test\..\test.txt
C:\JavaForTesters\test\..\test.txt
C:\JavaForTesters\test.txt
在这种情况下,我的假设是,即使所提供的路径不存在,由于路径包含“/../”,Java将其视为相对路径并在user.dir
中创建文件。所以这也是有道理的。
但是,如果我更新相对路径如下: @Test
public void testPathConversion() {
File f = new File("test/../../test.txt");
try {
f.createNewFile();
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
} catch (Exception e) {
e.printStackTrace();
}
}
然后我收到了IOException: Access is denied.
我的问题是:
- 为什么
"test/../test.txt"
被视为相对路径并在"user.dir"
中创建文件,但"test/../../test.txt"
返回错误?对于路径"test/../../test.txt"
,它试图在哪里创建文件? 当指定的相对路径未找到时,似乎文件被创建在
user.dir
中。所以,在我看来,下面两种情况做的事情是一样的://scenario 1 File f = new File("test/../test.txt"); f.createNewFile(); //scenario 2 File f = new File("test.txt"); f.createNewFile();
那么是否存在现实世界中的情况,人们会使用方案1而不是方案2呢?
我想我可能错过了一些显而易见的东西,或者基本上误解了相对路径。我查看了File的Java文档,但是找不到解释。Stack Overflow上有很多关于相对路径的问题,但我查找的那些都是针对特定情况而非关于如何解析相对路径的确切讨论。
如果有人能够解释这个问题或指向相关链接,那就太好了。
user.dir
是一个相当不稳定的变量位置,应用程序依赖它可能会很脆弱。另一个需要考虑的因素是,应用程序可能没有安装在具有写入权限的位置。更优化和健壮的方法是在user.home
(子目录中)创建文件。请参见此答案以获取简短示例。 - Andrew Thompsontest/test.txt
和test/../test.txt
都是相对路径。在这个意义上,相对路径与嵌入的..
组件无关。 - Boann