Java 在单例类中加载属性文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24962265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load Properties File in Singleton Class
提问by Thomas Moorer
I have seen this posted a couple of times and tried a few of the suggestions with no success (so far). I have a maven project and my properties file in on the following path:
我已经看到这个帖子发布了几次,并尝试了一些建议但没有成功(到目前为止)。我在以下路径中有一个 Maven 项目和我的属性文件:
[project]/src/main/reources/META_INF/testing.properties
I am trying to load it in a Singleton class to access the properties by key
我正在尝试将它加载到 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);
}
}
but I am getting a NullPointerError when this runs... I have done everything I can think of to the path, but it won't find/load the file.
但是当它运行时我得到一个 NullPointerError ......我已经做了我能想到的所有路径,但它不会找到/加载文件。
Any ideas?
有任何想法吗?
Stacktrace:
堆栈跟踪:
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)
采纳答案by M Anouti
You should instantiate your Properties
object. Also you should load the resource file with the path starting with /META-INF
:
你应该实例化你的Properties
对象。此外,您应该加载以以下开头的路径的资源文件/META-INF
:
properties = new Properties();
properties.load(getClass().getResourceAsStream("/META-INF/testing.properties"));
回答by T McKeown
properties
is null... you must first instantiate it.. then load it.
properties
为空...您必须先实例化它...然后加载它。