I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.
Questions:
You can load the property file suing the following way:
InputStream is = new Test().getClass().getClassLoader().getResourceAsStream("app.properties");
Properties props = new Properties();
props.load(is);
And then you can iterate over the map using a lambda expression like:
props.stringPropertyNames().forEach(key -> {
System.out.println("Key is :"+key + " and Value is :"+props.getProperty(key));
});
If you put the properties file in the same package as class Foo, you can easily load it with
new Properties().load(Foo.class.getResourceAsStream("file.properties"))
Given that Properties extends Hashtable you can iterate over the values in the same manner as you would in a Hashtable.
If you use the *.properties extension you can get editor support, e.g. Eclipse has a properties file editor.
In order:
Reading a properties file and loading its contents to Properties
String filename = "sample.properties";
Properties properties = new Properties();
input = this.getClass().getClassLoader().getResourceAsStream(filename);
properties.load(input);
The following is the efficient way to iterate over a Properties
for (Entry<Object, Object> entry : properties.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
In Java 8 to get all your properties
public static Map<String, String> readPropertiesFile(String location) throws Exception {
Map<String, String> properties = new HashMap<>();
Properties props = new Properties();
props.load(new FileInputStream(new File(location)));
props.forEach((key, value) -> {
properties.put(key.toString(), value.toString());
});
return properties;
}
Here is another way to iterate over the properties:
Enumeration eProps = properties.propertyNames();
while (eProps.hasMoreElements()) {
String key = (String) eProps.nextElement();
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}