【问题标题】:Load properties selectively from properties file based on key value根据键值从属性文件中选择性地加载属性
【发布时间】:2014-10-10 17:54:39
【问题描述】:

我有一个属性文件,它的值类似于

xxx.key1 = value1
xxx.key2 = value2

yyy.key3 = value3
yyy.key4 = value4

'xxx''yyy' 可以被视为 2 个不同的命名空间。 如何加载属性文件,以便我只能加载 'xxx''yyy' 的任一属性?

【问题讨论】:

  • 为什么不使用两个分开的属性文件?
  • 我们希望将用户必须配置的文件数保持为 1。否则配置会分散在多个地方

标签: java properties namespaces


【解决方案1】:

只需读取文件的每一行,然后只提取与该命名空间匹配的值。

Scanner scan = new Scanner(new File("yourfilepath"));
Map<String,String> map = new HashMap<String, String>();
String value = "";
while(scan.hasNext())
{
    value = scan.nextLine();
    if(value.indexOf("xxx") != -1)
    {
        map.put(value.split(" = ")[0], value.split(" = ")[1]);
    }
}

//now map has your key value pairs

如果你的属性是这样的

xxx.key1=值 然后在 split("=") (没有空格)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2015-12-15
    • 2017-10-10
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多