Reputation: 1486
I want to read a usual properties file and put the attribute and his value into a Map object. Technically, a properties file like
attr1=hello
attr2=java
attr3=world
would dynamically become a map object like this
+-------+-------+
+ K | V +
+-------+-------+
+ attr1 | hello +
+-------+-------+
+ attr2 | java +
+-------+-------+
+ attr3 | world +
+-------+-------+
In the end, it shouldn't matter what's in the properties file, the whole file will just be saved as a Map. Is it possible to do that with java.Properties or is a FileReader or an InputStream with special parsing necessary?
Upvotes: 0
Views: 2187
Reputation: 3475
java.util.Properties
also implements of Map
.
To load the properties from file, use Properties' load()
method with Reader
or InputStream
.
For instance,
Properties config = new Properties();
try {
config.load(<this.class>.getResourceAsStream(<property-file-name>)); //example input stream
//now can access it as a Map instance
config.get(<Key>);
config.entrySet();
//additionally, you can access Properties methods
config.getProperty(<property-name>);
} catch(...) {
...
}
If you want only Map
instance, let's say kind of Map<String, String>
, need to convert the properties to required map instance by iterating the property names.
Properties config = new Properties();
try {
config.load(<this.class>.getResourceAsStream(<property-file-name>)); //exampl input stream
Map<String, String> map = new HashMap<String, String>();
for (final String name: config.stringPropertyNames())
map.put(name, config.getProperty(name));
} catch(...) {
...
}
Upvotes: 1