在地图中存储属性文件 [英] Store properties file in map

查看:78
本文介绍了在地图中存储属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个普通的属性文件,并将该属性及其值放入Map对象中。
从技术上讲,是一个属性文件,例如

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 +
+-------+-------+



<最后,属性文件中的内容无关紧要,整个文件将被另存为Map。
是否可以使用java.Properties做到这一点,或者FileReader或需要特殊解析的InputStream?

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?

推荐答案

java.util.Properties 也实现了 Map

要从文件加载属性,请使用属性的 load()方法和 Reader InputStream

To load the properties from file, use Properties' load() method with Reader or 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>

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(...) {
    ...
}

这篇关于在地图中存储属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆