Reading Properties file in Java
I have the following code trying to read a properties file:
Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("myProp.properties");
prop.load(stream);
I get an exception at the last line. Specifically:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at Assignment1.BaseStation.readPropertyFile(BaseStation.java:46)
at Assignment1.BaseStation.main(BaseStation.java:87)
thanks, Nikos
Solution 1:
Based on your exception, the InputStream
is null, this means the class loader is not finding your properties file. I'm guessing that myProp.properties is in the root of your project, if that's the case, you need a preceding slash:
InputStream stream = loader.getResourceAsStream("/myProp.properties");
Solution 2:
You can find information on this page:
http://www.mkyong.com/java/java-properties-file-examples/
Properties prop = new Properties();
try {
//load a properties file from class path, inside static method
prop.load(App.class.getClassLoader().getResourceAsStream("config.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
}
catch (IOException ex) {
ex.printStackTrace();
}
Solution 3:
You can use ResourceBundle
class to read the properties file.
ResourceBundle rb = ResourceBundle.getBundle("myProp.properties");