java - 尝试获取属性文件时出现空指针

标签 java

我有一个 Maven 项目,其中包含文件 src/main/resources/barcoding.properties。当尝试使用以下代码获取 barcoding.properties 文件时,我不断收到以下代码的空指针:

public class BarcodingProperties{
  private static Properties props = null;

  private static void getProperties() {
        System.out.println("we in getProperties");
        props = new Properties();
        InputStream in = BarcodingProperties.class.getClass().getClassLoader().getResourceAsStream("barcoding.properties"); <-- This line returns null pointer exception.
        System.out.println("in. = "+in.toString());
        try {
            props.load(in);
        } catch (IOException e) {
            System.out.println("unable to load properties");
            e.printStackTrace();
        }
    }
}

当我构建项目并查看 jar 文件时,barcoding.properties 存在于项目根目录中。

为什么返回 null 以及如何修复它?

最佳答案

您正在尝试使用 Class 的类加载器来加载资源,而不是像这样的 BarcodingProperties:

BarcodingProperties.class.getClassLoader().getResourceAsStream("barcoding.properties");

Class的类加载器为null,表明它是由引导类加载器加载的,参见Stock JDK classes and the "null" ClassLoader?了解更多信息。

关于java - 尝试获取属性文件时出现空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19014387/

相关文章:

java - 如何配置maven hbm2hbmxml和hbm2java在mvn clean install中依次运行

java.net.SocketException : Software caused connection abort: recv failed

java - Java EE 应用程序中的用户首选项

java - 如何使用 SOAP Interceptor.get Understood Headers()?

java - Java 上的正则表达式日期格式验证

java - 从单链表中提取前 n 个元素

java - 在 java 中使用 PreparedStatement 的正确方法是什么?

java - 在不依赖集合的情况下从对象列表中删除重复项

java - Android Edittext Onclick Datepickerdialog Lollipop 中出现错误

java - GSON - 具有命名策略的可选和必填字段