Reputation: 33
I have an application that implements a JTree and populates the tree with a java properties file as default; The nodes are the keys and the values are the contents of the node. The application was designed to be dynamic so a JButton and JTextField are implemented to take in new values and put the values in the exists keys in the properties file.
So for example I have the line below as a default value in a sample.properties file
node=cat,dog,mice
and using the JTextField and JButton I input "rabbit" to append to the node, to look like:
node=cat,dog,mice,rabbit
I've implemented JTextField and JButton and have them working but I just can't seem to find a good way to append new values to existing keys in the properties file.
Upvotes: 3
Views: 10010
Reputation: 81
I would look at Apache Commons Configuration. It has very specific examples that do what you are asking.
Try:
import org.apache.commons.configuration.PropertiesConfiguration;
PropertiesConfiguration config = new PropertiesConfiguration(
"config.properties");
config.setProperty("my.property", somevalue);
config.save();
Upvotes: 1
Reputation: 9935
Just FileWriter
FileWriter fileWritter = new FileWriter("example.properties", true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append("PROPERTES_YOUR_KEY=PROPERTES_YOUR_VALUE");
bufferWritter.close();
Update
Properties API does not support, I am not sure why you need this functionality.
You can try as below :
example.properties
PROPERTIES_KEY_3=PROPERTIES_VALUE_3
PROPERTIES_KEY_2=PROPERTIES_VALUE_2
PROPERTIES_KEY_1=PROPERTIES_VALUE_1
Program
Properties pop = new Properties();
pop.load(new FileInputStream("example.properties"));
pop.put("PROPERTIES_KEY_3", "OVERWRITE_VALUE");
FileOutputStream output = new FileOutputStream("example.properties");
pop.store(output, "This is overwrite file");
output
PROPERTIES_KEY_3=OVERWRITE_VALUE
PROPERTIES_KEY_2=PROPERTIES_VALUE_2
PROPERTIES_KEY_1=PROPERTIES_VALUE_1
Upvotes: 3