2014-11-03 119 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

相关问题