`getResourceAsStream("config.properties")` - **this method will only work if your properties file is in the classpath. I think you have added the properties file outside the classpath. This method is basically used for accessing a file present in the classpath.**
**Please check it again.**
Thanks :)
Working Code :
public class MyClass {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "config.properties";
input = MyClass.class.getClassLoader().getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
// load a properties file from class path, inside static method
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("serverUrl"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
1) It is good to have your property file in classpath but you can place it anywhere in project.
Below is how you load property file from classpath and read all properties.
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "path to property file";
input = getClass().getClassLoader().getResourceAsStream(filename);
if (input == null) {
System.out.println("Sorry, unable to find " + filename);
return;
}
prop.load(input);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2) Property files have the extension as .properties