我想了解Java在创建File
对象时解析相对路径的方式。Java如何在新File()中解析相对路径?
OS使用:视窗
对于下面的代码片段,我得到了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();
}
}
我的理解这里,爪哇将其视为绝对回报提供的路径路径不存在时发生错误。所以这是有道理的。
当我更新了上面的代码中使用相对路径:
@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异常:访问被拒绝。
我的问题是:
- 为什么
"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();
那么,有没有一个真正的世界的案例,其中一个会用,而不是场景2场景1?
我想我错过了一些很明显的东西,或者从根本上误解了相对路径。我浏览了File的Java文档,但无法找到解释。关于相对路径,在Stack Overflow中发布了相当多的问题,但是我查找的是针对特定场景的,而不是关于如何解析相对路径。
如果有人能解释我这是如何工作的或指向一些相关链接,这将是非常好的吗?
请注意,'user.dir'是一个很不稳定的地方,它应该依赖于脆弱。另一个需要考虑的因素是应用程序。可能没有安装在它有*写权限的地方。**将文件放在'user.home'(的子目录)中会更加优化和健壮。请参阅[这个答案](http://stackoverflow.com/a/10166623/418556)一个简短的例子。 –
注意:'test/test.txt'和'test /../ test.txt'都是相对路径。这个意义上的相对与嵌入式“..”组件的存在无关。 – Boann