我想读取一个常用的属性文件并将属性及其值放入 Map 对象中。 从技术上讲,属性文件类似于
attr1=hello
attr2=java
attr3=world
会动态地变成这样的 map 对象
+-------+-------+
+ K | V +
+-------+-------+
+ attr1 | hello +
+-------+-------+
+ attr2 | java +
+-------+-------+
+ attr3 | world +
+-------+-------+
最后,属性文件中的内容并不重要,整个文件将被保存为 map 。 是否可以使用 java.Properties 来做到这一点,或者需要进行特殊解析的 FileReader 或 InputStream 吗?
最佳答案
java.util.Properties
还实现了Map
。
要从文件加载属性,请使用 Properties' load()
方法 Reader
或InputStream
.
例如,
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(...) {
...
}
如果你只想要Map
例如,假设是 Map<String, String>
,需要通过迭代属性名称将属性转换为所需的map实例。
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(...) {
...
}
关于java - 将属性文件存储在 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24280226/