IntelliJ:资源的非绝对(相对)路径

Dav*_*lva 5 java intellij-idea

我有这样的代码:

public class EntryPoint {
    public static void main(String args[]) {
        File file = new File("resources/file.xml");
        try {
            Document document = new SAXReader().read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

我的测试模块的结构如下:

我的测试模块的结构

问题是我收到错误:

嵌套异常:java.io.FileNotFoundException:resources\file.xml

当然我可以改变路径,例如这样:

File file = new File("C:/ws/_SimpleTests/resources/file.xml");
Run Code Online (Sandbox Code Playgroud)

它可以正常工作,但我不想使用绝对路径。

我应该在 IntelliJ 中设置什么才能使用相对路径?

Spa*_*kOn 5

首先右键单击资源文件夹 -> 将目录标记为 -> 资源根目录,然后尝试以这种方式读取文件

InputStream is = TestResources.class.getClassLoader().getResourceAsStream("file.xml");
Run Code Online (Sandbox Code Playgroud)

或者

File file = new File(YourClassName.class.getClassLoader().getResource("file.xml")
                                                         .getPath());
Run Code Online (Sandbox Code Playgroud)


sol*_*4me 2

您可以使用Pathsfile.xml像这样检索

File file = Paths.get(".", "resources", "file.xml").normalize().toFile();
Run Code Online (Sandbox Code Playgroud)