udy*_*udy 18 java inputstream nullpointerexception
我使用以下代码来读取属性文件:
Properties pro = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().
getResourceAsStream("resources.properties");
pro.load(is);
Run Code Online (Sandbox Code Playgroud)
当我执行代码时,我收到以下错误:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at com.ibm.rqm.integration.RQMUrlUtility.RQMRestClient.getResource(RQMRestClient.java:66)
at com.ibm.rqm.integration.RQMUrlUtility.RQMRestClient.main(RQMRestClient.java:50)
Run Code Online (Sandbox Code Playgroud)
为什么我得到了NullPointerException?我应该在哪里保存resources.properties文件?
pol*_*nts 19
它看起来像ClassLoader.getResourceAsStream(String name)返回null,然后导致Properties.load抛出NullPointerException.
以下是文档的摘录:
URL getResource(String name):查找具有给定名称的资源.资源是一些数据(图像,音频,文本等),可以通过类代码以独立于代码位置的方式访问.资源的
'/'名称是标识资源的分离路径名.返回:一个
URL对象读取资源,或者null如果:
- 无法找到资源,或
- 调用者没有足够的权限来获取资源.
getResource
如果你写更多行,错误修正会更容易,例如:
Properties properties = new Properties();
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
InputStream propertiesStream = contextClassLoader.getResourceAsStream("resource.properties");
if (propertiesStream != null) {
properties.load(propertiesStream);
// TODO close the stream
} else {
// Properties file not found!
}
Run Code Online (Sandbox Code Playgroud)