小编Esw*_*war的帖子

Java如何解析新File()中的相对路径?

我试图了解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();
        }
}
Run Code Online (Sandbox Code Playgroud)

我的理解是,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();
        }    
    }
Run Code Online (Sandbox Code Playgroud)

它创建一个新文件并提供以下输出:

test\..\test.txt
C:\JavaForTesters\test\..\test.txt
C:\JavaForTesters\test.txt
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我的假设是,即使提供的路径不存在,因为路径包含"/../",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()); …
Run Code Online (Sandbox Code Playgroud)

java file relative-path

40
推荐指数
4
解决办法
13万
查看次数

标签 统计

file ×1

java ×1

relative-path ×1