Reputation: 5235
What is the best way to load a property file when path to the property file is not fixed and provided via command line arguments?
I am using the following code to load it but it is giving me null pointer exception when run using command line arguments:
Properties p = new Properties();
p.load(testClass.class.getResourceAsStream("path to the property file"));
Upvotes: 2
Views: 5027
Reputation: 716
If you get the (full) path via command line, you jsut need to provide a reader or input stream with that path. In the end, your code could look like this:
public static void main(String[] args) {
System.out.println("reading property file " + args[0]);
// create new initial properties
Properties properties = new Properties();
// open reader to read the properties file
try (FileReader in = new FileReader(args[0])){
// load the properties from that reader
properties.load(in);
} catch (IOException e) {
// handle the exception
e.printStackTrace();
}
// print out what you just read
Enumeration<?> propertyNames = properties.propertyNames();
while(propertyNames.hasMoreElements()) {
String name = propertyNames.nextElement().toString();
System.out.println(name + ": " + properties.getProperty(name));
}
}
Upvotes: 3