尝试获取属性文件时的Nullpointer

时间:2013-09-25 20:14:41

标签: java

我有一个文件src/main/resources/barcoding.properties的maven项目。在尝试使用以下代码获取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,我该如何解决呢?

2 个答案:

答案 0 :(得分:2)

这看起来很奇怪:

BarcodingProperties.class.getClass()

BarcodingProperties.class是BarcodingProperties类对象实例。如果你对它做一个getClass(),它将返回Class类对象...

Ideone fiddle但是使用String.class

你想要的可能是:

InputStream in = BarcodingProperties.class.getClassLoader().getResourceAsStream("barcoding.properties");

答案 1 :(得分:2)

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

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

Class的类加载器为null,表示它是由引导类加载器加载的,有关详细信息,请参阅Stock JDK classes and the "null" ClassLoader?