在 Java 中读取属性文件时出现 NullPointerException [英] NullPointerException when reading a properties file in Java
问题描述
我正在使用以下代码读取属性文件:
I am using the following code to read a properties file:
Properties pro = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().
getResourceAsStream("resources.properties");
pro.load(is);
当我执行代码时,我收到以下错误:
And when I execute the code I'm getting the following error:
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)
为什么我会收到 NullPointerException
?我应该在哪里保存 resources.properties
文件?
Why am I getting a NullPointerException
? And where should I save the resources.properties
file?
推荐答案
看起来像 ClassLoader.getResourceAsStream(String name)
返回 null
,然后导致 Properties.load
抛出 NullPointerException
.
It looks like ClassLoader.getResourceAsStream(String name)
returns null
, which then causes Properties.load
to throw NullPointerException
.
以下是文档摘录:
URL getResource(String name)
:查找具有给定名称的资源.资源是一些数据(图像、音频、文本等),可以通过类代码以独立于代码位置的方式访问.
URL getResource(String name)
: Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.
资源的名称是一个以 '/'
分隔的路径名,用于标识资源.
The name of a resource is a '/'
-separated path name that identifies the resource.
返回:一个用于读取资源的URL
对象,或者null
如果:
Returns: A URL
object for reading the resource, or null
if:
- 找不到资源,或
- 调用者没有足够的权限来获取资源.
另见
- Java 教程/使用
getResource 加载图像
- 有示例说明在目录/JAR 文件中的何处/如何放置和访问资源
这篇关于在 Java 中读取属性文件时出现 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!