Java properties file adds new values

I have an application that implements JTree and populates the tree with the default java properties file; Nodes are keys, and values ​​are the contents of node. The application was designed to be dynamic, so JButton and JTextField are implemented to enter new values ​​and put the values ​​in existing keys in the properties file.

So, for example, I have the line below as the default in the sample.properties file

node = cat, dog, mouse

and using JTextField and JButton I, enter β€œrabbit” to add to node to look like this:

node = cat, dog, mouse, rabbit

I implemented JTextField and JButton and made them work, but I just can't find a good way to add new values ​​to existing keys in the properties file.

+3
source share
2 answers

Simply FileWriter

FileWriter fileWritter = new FileWriter("example.properties", true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append("PROPERTES_YOUR_KEY=PROPERTES_YOUR_VALUE");
bufferWritter.close();

Refresh

The property API is not supported, I'm not sure why this functionality is needed.
You can try the following:

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");

Exit

PROPERTIES_KEY_3=OVERWRITE_VALUE
PROPERTIES_KEY_2=PROPERTIES_VALUE_2
PROPERTIES_KEY_1=PROPERTIES_VALUE_1
+3
source

I would take a look at the Apache Commons Configuration . It has very specific examples that do what you ask.

Try:

import org.apache.commons.configuration.PropertiesConfiguration;

PropertiesConfiguration config = new PropertiesConfiguration(
    "config.properties");

config.setProperty("my.property", somevalue);

config.save();
+1
source

Source: https://habr.com/ru/post/1610323/


All Articles