Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

java 使用相对路径时,File::exist 是基于什么寻找文件的?

图片.png

默认情况下,java.io 包中的类总是根据当前用户目录来解析相对路径名。此目录由系统属性 user.dir 指定,通常是 Java 虚拟机的调用目录。
@Test
public void test02() throws IOException {
    String relativePath = "target/test-classes/data/file01.txt";
 // debug maven test 时:
 // user.dir 为 E:DocumentsIdeaProjectsMyWorkSpaceprj01modelA // file.exists() 为 false // file.getAbsoluteFile.exists() 为 true System.out.println("original user.dir is: " + System.getProperty("user.dir"));
 File file = new File(relativePath);
 System.out.println("tfile exist: " + file.exists() +
            "nttpath=" + file.getPath() +
            "nttabsolutePath=" + file.getAbsolutePath() +
            "nttabsolutrFile exist:" + file.getAbsoluteFile().exists());
 // 修改 user.dir 为 e:/ 后:
 // file.exists() 为 false // file.getAbsoluteFile.exists() 为 false System.setProperty("user.dir", "e:/");
 System.out.println("after change user.dir is: " + System.getProperty("user.dir"));
 File file1 = new File(relativePath);
 System.out.println("tfile exist: " + file1.exists() +
            "nttpath=" + file1.getPath() +
            "nttabsolutePath=" + file1.getAbsolutePath() +
            "nttabsolutrFile exist:" + file.getAbsoluteFile().exists());
}

但是这里修改了 user.dir 后,File::exist 还是存在,但是getAbsoluteFile 不存在。


上述问题是在思考下面的问题时的一些不解之处:

使用了相对路径的模型在其父模块执行 debug maven test 而导致的错误

项目目录结构如下:

目录结构

测试代码如下:

public class TempTest {

    @Test
    public void test01() {
        String filePath = "target/test-classes/data/file01.txt";
        File file = new File(filePath);
        boolean exists = file.exists();
        System.out.println(exists);
        Assert.assertTrue(exists);

    }
} 

在 modelA 执行 run maven test

model A执行 run maven test

成功。

在父模块执行run maven test

父模块prj01执行 run maven test

成功。

在modelA执行debug maven test

modelA 执行 debug maven test

成功。

在父模块执行debug maven test

父模块prj01执行 debug maven test

执行失败。



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

File的很多操作和user.dir并没有关系
getAbsolutePath/File 才会用到 user.dir
修改user.dir只会影响getAbsolutePath/File,对new File(path)和其他很多操作没有影响


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...