2014-09-22 38 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());