2014-11-03 117 views
0

我的項目設置是這樣的: enter image description here無法找到項目文件夾中的JSON文件

現在我嘗試引用report.json文件中像這樣的MainFrameTest.java內:

Template template = new JsonTemplate(Thread.currentThread(). 
      getContextClassLoader().getResource("/report.json").toURI()); 

我也試過:

Template template = new JsonTemplate(Thread.currentThread(). 
     getContextClassLoader().getResource("report.json").toURI()); 

而完整路徑:

Template template = new JsonTemplate(Thread.currentThread(). 
     getContextClassLoader().getResource("C:/prohes/esc_print_test/report.json").toURI()); 

但我總是得到這個錯誤:

java.lang.NullPointerException 
at esc_print_test.MainFrameTest.<init>(MainFrameTest.java:28) 
at esc_print_test.MainFrameTest.main(MainFrameTest.java:55) 

什麼我錯了嗎?謝謝

+0

什麼是'MainFrameTest.java'在28? – Deepak 2014-11-03 12:10:14

+0

在'28'中有'getContextClassLoader()。getResource(「/ report.json」)。toURI()); ' – 2014-11-03 12:10:48

+0

首先嚐試打印您所在的位置,然後可以獲取該文件。 – Krishna 2014-11-04 07:24:06

回答

2

嘗試罰款第一個當前目錄,然後你可以給這些資源。

這樣做會給你當前的文件夾地址。

String name = new File(".").getCanonicalPath(); 
System.out.println("Test "+ name); 

然後你可以擁有文件,因爲你已經定義了路徑。

用於獲取該路徑中的新文件做類似這樣的事情。

File file = new File(name, "/"+ "yourfilename.extension"); 

希望這有助於。

和幸福的另一種選擇是

URI file = new File(name, "/"+ "one.text").toURI(); 
      System.out.println(file); 
1

將json文件放在src文件夾中,並直接在getContextClassLoader().getResource("report.json")中使用。

編輯:

我在日食試過這樣:

public static void main(String arg[]){ 
     System.out.println("test="+Thread.currentThread().getContextClassLoader().getResource("report.json")); 
    } 

輸出:

test=file:/D:/liferay/BundleTomcat/workspace/springBatch/target/classes/report.json 

只是要確保檢查report.json文件存在於目標存在.class文件的文件夾。

+0

對不起,但我得到同樣的錯誤! – 2014-11-03 12:15:03

+0

將json文件放入src文件後,試試這個:MainFrameTest.class.getClassLoader()。getResource(「/ report.json」); – 2014-11-03 12:43:02

+0

也可以在這裏找到有關從src文件夾加載的更多信息:http://stackoverflow.com/questions/17865427/load-a-file-from-src-folder-into-a-reader – Vishnu 2014-11-04 06:12:55

相關問題