在Singleton类中加载属性文件

问题描述

您应该实例化您的Properties对象。另外,您还应该使用以下路径加载资源文件/META-INF

properties = new Properties();
properties.load(getClass().getResourceAsStream("/META-INF/testing.properties"));

解决方法

我已经看过几次,并尝试了一些建议,但都没有成功(到目前为止)。我在以下路径上有一个maven项目和属性文件:

[project]/src/main/reources/META_INF/testing.properties

我正在尝试将其加载到Singleton类中以通过键访问属性

public class TestDataProperties {

    private static TestDataProperties instance = null;
    private Properties properties;


    protected TestDataProperties() throws IOException{

        properties = new Properties();
        properties.load(getClass().getResourceAsStream("testing.properties"));

    }

    public static TestDataProperties getInstance() {
        if(instance == null) {
            try {
                instance = new TestDataProperties();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        return instance;
    }

    public String getValue(String key) {
        return properties.getProperty(key);
    }

}

但是我在运行时遇到了NullPointerError的问题。我已经完成了所有可以想到的操作,但是无法找到/加载文件。

有任何想法吗?

堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...