2014-09-22 139 views
1

我有这样的代码:的IntelliJ:非绝对(相对)路径资源

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(); 
     } 
    } 

} 

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

structure of my test module

的问题是,我得到错误:

Nested exception: java.io.FileNotFoundException: resources\file.xml

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

File file = new File("C:/ws/_SimpleTests/resources/file.xml"); 

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

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

+0

这与intellij有什么关系? – 2014-09-22 16:16:42

+0

@ david-silva,你有没有找到解决办法? – 2016-05-16 17:27:14

回答

2

您可以使用Paths检索file.xml这样

File file = Paths.get(".", "resources", "file.xml").normalize().toFile(); 
+0

这与原始代码不完全相同吗? – kaqqao 2014-09-22 17:09:59

2

首先在资源文件夹rght点击 - >标记目录 - >资源根然后 尝试读取文件这样

InputStream is = TestResources.class.getClassLoader().getResourceAsStream("file.xml"); 

File file = new File(YourClassName.class.getClassLoader().getResource("file.xml") 
                 .getPath());