2013-04-09 87 views
1

我有一个特性在位置文件(从NetBeans项目资源管理器)找不到属性文件 - 如何找到它作为资源?

-MyTest 
    +Web Pages 
    +Source Packages 
    -Test Packages 
     -<default package> 
      +Env.properties  <---- Here it is 
     +com.mycomp.gts.test 
     +com.mycomp.gts.logintest 
     ..... 
     .... 

现在,当我试图使用代码

InputStream propertiesInputStream = getClass().getResourceAsStream("Env.properties"); 
ENV.load(propertiesInputStream); 

它扔java.lang.NullPointerException

+0

此答案可能有助于您的情况:http://stackoverflow.com/a/8854824/122442 – 2013-04-09 06:34:33

回答

6

你不能用它来找到这个文件该类作为加载资源的参考,因为资源路径是而不是相对于该类。使用的类加载器来代替:

InputStream propertiesInputStream = getClass().getClassLoader() 
     .getResourceAsStream("Env.properties"); 
ENV.load(propertiesInputStream); 

或者,你可以使用当前线程的上下文类加载器:

InputStream propertiesInputStream = Thread.currentThread() 
    .getContextClassLoader().getResourceAsStream("Env.properties"); 
ENV.load(propertiesInputStream); 
+1

同样的错误.... java.lang.NullPointerException – coure2011 2013-04-09 06:25:44

+0

您正在运行测试包中的代码吗? – Perception 2013-04-09 06:38:11

+0

yes右击测试方法并运行测试 – coure2011 2013-04-09 06:45:51

1
String basePath = PropertiesUtil.class.getResource("/").getPath(); 
InputStream in = new FileInputStream(basePath + "Env.properties"); 
pros.load(in); 

祝你好运:)

+0

什么是PropertiesUtil? netbeans用红色表示它 – coure2011 2013-04-09 06:29:58

+0

它指的是任何类都可以。 – 2013-04-09 06:31:50

+0

构建失败:无法找到符号类PropertiesUtil – coure2011 2013-04-09 06:34:38

1

尝试获得绝对路径与:

String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm(); 

您可以打印出字符串absolute并尝试将其子串绑定到属性文件的路径。