IDEA 使用 File 类时使用相对路径找不到文件的问题

一句话,IDEA 把项目根目录看作相对路径的起点。

把项目根目录看作相对路径的起点即可。

以下是可能出错的情况:

用 Jetbrain 的 IDE,不管是 IDEA 还是 CLion 都遇到明明感觉要读取的文件就在当前目录,但是一直报错这不到。

事实上 IDE 找文件的时候是在 workspace 目录下找的。而我保存在了 workspace/src 下。

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package me.lgp.java.jdk.io.file;

import org.junit.Test;

import java.io.File;

public class FileOutputStreamTest {

@Test
public void test1() {
System.out.println("new File(\".\").getPath() = " + new File(".").getAbsolutePath());
System.out.println("System.getProperty(\"user.dir\") = " + System.getProperty("user.dir"));
File file1 = new File(System.getProperty("user.dir") + "/src/test/resources/me/lgp/java/jdk/io/file/file.temp");
File file2 = new File("./src/test/resources/me/lgp/java/jdk/io/file/file.temp");
System.out.println("file1.exists() = " + file1.exists());
System.out.println("file2.exists() = " + file2.exists());
}
}

输出为:

1
2
3
4
new File(".").getPath() = C:\Users\Peng\Desktop\开发\projects\useful-java-snippets\java-lang\.
System.getProperty("user.dir") = C:\Users\Peng\Desktop\开发\projects\useful-java-snippets\java-lang
file1.exists() = true
file2.exists() = true

参考资料

  1. IntelliJ IDEA 相对路径查找文件问题?