【问题标题】:Load Properties File in Singleton Class在单例类中加载属性文件
【发布时间】:2014-09-17 16:39:19
【问题描述】:

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

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

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

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)

【问题讨论】:

  • 请添加stackstrace 并将我们指向它抛出exception 的那一行。
  • 我会质疑你的属性文件的结构。堆栈跟踪错误不是来自你的代码

标签: java maven properties classpath


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    properties 为空……你必须先实例化它……然后加载它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-18
      • 2013-09-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      相关资源
      最近更新 更多