我试图了解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:访问被拒绝。
我的问题是:
"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中有很多关于相对路径的问题,但是我查询的是针对特定场景的,而不是关于如何解决相对路径的。
如果有人可以解释我的工作原理或指向一些相关链接,那将是很好的选择?
有一个概念working directory
。
该目录由.
(点)表示。
在相对路径中,其他所有东西都是相对的。
只需将.
(工作目录)放在运行程序的位置。
在某些情况下,可以更改工作目录,但是通常这是
点代表的意思。我认为这是C:\JavaForTesters\
您的情况。
于是test\..\test.txt
方式:子目录test
在我的工作目录,再向上一个级别,那么
文件test.txt
。这基本上与just相同test.txt
。
有关更多详细信息,请点击此处。
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句