Load Properties File in Singleton Class
14,869
Solution 1
You should instantiate your Properties
object. Also you should load the resource file with the path starting with /META-INF
:
properties = new Properties();
properties.load(getClass().getResourceAsStream("/META-INF/testing.properties"));
Solution 2
properties
is null... you must first instantiate it.. then load it.
Author by
Thomas Moorer
Updated on June 04, 2022Comments
-
Thomas Moorer almost 2 years
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:
[project]/src/main/reources/META_INF/testing.properties
I am trying to load it in a Singleton class to access the properties by key
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.
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)