在Java中读取属性文件时出现NullPointerException [英] NullPointerException when reading a properties file in Java

查看:816
本文介绍了在Java中读取属性文件时出现NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码读取属性文件:

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 ,然后导致属性。加载抛出 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 if:

Returns: A URL object for reading the resource, or null if:


  • 无法找到资源,或者

  • 调用者没有足够的权限来获取资源。



参见




  • Java教程/使用 getResource


    • 有关于在目录/ JAR文件中放置和访问资源的位置/方式的示例

    • 这篇关于在Java中读取属性文件时出现NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆