简体   繁体   English

在地图中存储属性文件

[英]Store properties file in map

I want to read a usual properties file and put the attribute and his value into a Map object. 我想读取一个普通的属性文件,并将属性及其值放入Map对象中。 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. 最后,属性文件中的内容无关紧要,整个文件将仅保存为Map。 Is it possible to do that with java.Properties or is a FileReader or an InputStream with special parsing necessary? 是否可以使用java.Properties做到这一点,或者需要FileReader或具有特殊解析的InputStream吗?

java.util.Properties also implements of Map . java.util.Properties还实现Map

To load the properties from file, use Properties' load() method with Reader or InputStream . 要从文件加载属性,请将属性的load()方法与ReaderInputStream

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. 如果只需要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(...) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM