Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Properties: Add new keys to properties file in run time?

Is it possible to create a new properties file and add keys and values in run time? I want to add new keys to properties file depending on user input while installing my application. I checked out Java Properties class but it seem it can set values to existing keys but can not add new keys to properties file.

like image 680
Olcay Ertaş Avatar asked Sep 27 '11 14:09

Olcay Ertaş


People also ask

How do you update a properties file dynamically in Java?

properties file. Instantiate the Properties class. Populate the created Properties object using the put() method. Instantiate the FileOutputStream class by passing the path to store the file, as a parameter.

How do I add to properties file?

Create a properties fileRight-click and select Add New Properties File. A new properties file will be added to your project. The new file will be selected and highlighted in the list. Type a name for your properties file, for example, "Properties".

How set value in properties file in Java?

To set properties in a Java Properties instance you use the setProperty() method. Here is an example of setting a property (key - value pair) in a Java Properties object: properties.


1 Answers

You can add new properties just by calling setProperty with a key which doesn't currently exist. That will only do it in memory though - you'll have to call store again to reflect the changes back to a file:

Properties prop = new Properties();
prop.load(...); // FileInputStream or whatever

prop.setProperty("newKey", "newValue");
prop.store(...); // FileOutputStream or whatever
like image 69
Jon Skeet Avatar answered Oct 06 '22 00:10

Jon Skeet