从jar文件加载属性文件时出错

时间:2013-08-23 10:27:50

标签: java properties embedded-resource

我正在尝试从jar文件中加载属性文件但不能这样做。 以下是我正在加载文件的类的代码

public class PropertyClass {
    private static Properties properties;

    public String getProperty(String propertyName)  {
        try {
            InputStream inputStream =   this.getClass().getClassLoader().getResourceAsStream("resources/test.properties");

            System.out.println("Input Stream " + inputStream);
            properties.load(inputStream);

            inputStream.close();
            if (properties == null) {
                System.out.println("Properties null");
            }
        } catch (IOException e){
            e.printStackTrace();
        }
        return properties.getProperty(propertyName);
    }
}

类文件和属性文件都打包在jar中。但是当我尝试从另一个方法加载文件时,它会出现以下错误: -

Input Stream - sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream@9304b1
Exception in thread "main" java.lang.NullPointerException
at PropertyClass.getProperty(PropertyClass.java:16)

它不会将输入流显示为null 以下位是我的代码中的第16行 - properties.load(的inputStream);

对此有任何帮助

1 个答案:

答案 0 :(得分:3)

您需要先初始化Properties对象,然后才能拨打properties.load()

private static Properties properties = new Properties();
相关问题