Java:将值附加到 属性 键

Java: Append Value to Property Key

我正在使用 java.util.Properties 将属性存储在文件中。我可以使用以下代码成功存储 key/value 对:

public String setKeyValue(String dir, String key, String value) throws FileNotFoundException, IOException
{
    File file = new File(dir);


    FileInputStream in = new FileInputStream(file);
    Properties properties = new Properties();
    properties.load(in);
    in.close();

    FileOutputStream out = new FileOutputStream(file);
    properties.setProperty(key, value);
    properties.store(out, null);
    out.close();

    String myValue = (String) properties.getProperty(key);
    System.out.println (myValue);
    return myValue;
}

但是,我有兴趣更新(而不是替换)以前的 属性,这样我以后可以将它们作为数组检索。

例如我当前的 属性 看起来像这样:

email=email1 

我想改成

email=email1, email2 //(this will be a continuous process of adding more emails)

这样我以后可以按如下方式检索它们:

String[] emailList = properties.getProperty("email").split(","); 

如果您使用以前的代码,它只是替换 属性。我需要附加额外的 "value" 到 key..

嗯,最简单的方法就是这样做...

String oldValue = properties.getProperty( key );
String newValue = "bla something";
String toStore = oldValue != null ? oldValue + "," + newValue : newValue;
properties.setProperty( key, value );

当然,这不是很优雅,所以我个人可能会从 Properties 扩展我自己的 AppenderProperties class,然后添加一个 append 方法。这也是放置所有与数组相关的方法的好地方,这样您就可以从键等中删除特定的值。