【发布时间】:2014-01-30 09:51:07
【问题描述】:
我试图了解 Java 在创建 File 对象时解析相对路径的方式。
使用的操作系统:Windows
对于下面的 sn-p,我得到一个 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的(子目录)中会更加优化和健壮。有关简短示例,请参阅 this answer。 -
注意:
test/test.txt和test/../test.txt都是相对路径。这个意义上的相对与嵌入的..组件的存在无关。
标签: java file relative-path