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

执行失败。


阅读 2.6k
2 个回答

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

这是因为你通过System.setProperty("user.dir")不会真的改变user.dir,可以换一种测试方法,加入测试类是

public class T {
    public static void main(String[] args) {
        File f = new File("bbbb.txt");
        System.out.println(f.exists());
        
        File f1 = new File("aaaa.txt");
        System.out.println(f1.exists());

    }
}

其中aaaa.txt和bbbb.txt文件分别位于D:a和D:b目录下,T.class位于D:,你在D:a目录下执行命令java -cp D: T,打印的结果会是false,true,然后再切换到D:b目录下执行java -cp D: T,结果就会是true,false

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题