如何解决在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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。