gpt4 book ai didi

java - 将属性文件存储在 map 中

转载 作者:行者123 更新时间:2023-12-01 12:50:12 25 4
gpt4 key购买 nike

我想读取一个常用的属性文件并将属性及其值放入 M​​ap 对象中。从技术上讲,属性文件类似于

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()方法 ReaderInputStream .

例如,

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com