Reputation: 41
I am using java.util.Properties to store properties in a file. I am able to store key/value pair successfully using the following code:
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;
}
However, I am interested in updating (not replacing) a previous property so I can later retrieve them as an array.
For example my current property looks something like this:
email=email1
I want to change it to
email=email1, email2 //(this will be a continuous process of adding more emails)
This way I can later retrieve them as follows:
String[] emailList = properties.getProperty("email").split(",");
If you use the previous code it simply replaces the property. I need to append additional "value" to key..
Upvotes: 0
Views: 1990
Reputation: 10652
Well, the most simple way would be do this...
String oldValue = properties.getProperty( key );
String newValue = "bla something";
String toStore = oldValue != null ? oldValue + "," + newValue : newValue;
properties.setProperty( key, value );
Of course, that's not very elegant, so I personally would probably extend my own AppenderProperties
class from Properties
and then add an append
method. This would also be a good place to put all the array-related methods, so that you can remove specific values from your keys, etc.
Upvotes: 1