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

标签 java dictionary properties config

我想读取一个常用的属性文件并将属性及其值放入 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/

相关文章:

java - 不幸的是停止了这个应用程序

java - 如何添加整数构造函数和公共(public)签名java

python - 在 Python 3 中将字典列表转换为 CSV

ios - 在 Swift 中运行两次的检查数据和存储数据的代码

c++ - 打印出映射键值,其中键是结构变量 c++

ios - 如果我没有在 viewDidUnload 方法中设置属性 = nil,这意味着什么?

java - 将 PDF 文件转换为单个 HTML 文件

java - 运行依赖项 : java could not find or load the main class OSMImportTool 的 jar 文件

Python - 缓存一个属性以避免 future 的计算

delphi - 克隆 TStringGrid 组件