Java IntelliJ:资源的非绝对(相对)路径
我有这样的代码:Java IntelliJ:资源的非绝对(相对)路径,java,intellij-idea,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) {
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();
}
}
}
File file = new File("C:/ws/_SimpleTests/resources/file.xml");
我的测试模块的结构如下:
问题是我得到了一个错误:
嵌套异常:java.io.FileNotFoundException:resources\file.xml
当然,我可以改变路径,例如:
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();
}
}
}
File file = new File("C:/ws/_SimpleTests/resources/file.xml");
它可以正常工作,但我不想使用绝对路径
我应该在IntelliJ中设置什么来使用相对路径?您可以像这样使用来检索file.xml
File file = Paths.get(".", "resources", "file.xml").normalize().toFile();
首先单击资源文件夹->将目录标记为->资源根目录,然后单击
尝试以这种方式读取文件
InputStream is = TestResources.class.getClassLoader().getResourceAsStream("file.xml");
或
这和intellij有什么关系?