You need to use \n\ as a solution. First two symbols \n - new line for string, third \ - multi-line in properties file. For example (in application.
Just do not open the file in append mode. You read existing properties from the file and the write them again. If you append to the file, all the contents of the Properties object will be appended since this is what you asked for. FileOutputStream fileOut = new FileOutputStream(file,true);
The Properties
API doesn't provide any methods for adding/replacing/removing a property in the properties file. The model that the API supports is to load all of the properties from a file, make changes to the in-memory Properties
object, and then store all of the properties to a file (the same one or a different one).
But the Properties
API is not unusual in the respect. In reality, in-place updating of a text file is difficult to implement without rewriting the entire file. This difficulty is a direct consequence of the way that files / file systems are implemented by a modern operating system.
If you really need to do incremental updates, then you need to use some kind of database to hold the properties, not a ".properties" file.
Other Answers have suggested the following approach in various guises:
Properties
object.Properties
object.Properties
object on top of existing file.This works for some use-cases. However the load / save is liable to reorder the properties, remove embedded comments and white space. These things may matter1.
The other point is that this involves rewriting the entire properties file, which the OP is explicitly trying to avoid.
1 - If the API is used as the designers intended, property order, embedded comments, and so on wouldn't matter. But lets assume that the OP is doing this for "pragmatic reasons".
You can use PropertiesConfiguration from Apache Commons Configuration.
In version 1.X:
PropertiesConfiguration config = new PropertiesConfiguration("file.properties");
config.setProperty("somekey", "somevalue");
config.save();
From version 2.0:
Parameters params = new Parameters();
FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.properties()
.setFileName("file.properties"));
Configuration config = builder.getConfiguration();
config.setProperty("somekey", "somevalue");
builder.save();
Properties files are an easy way to provide configuration for an application, but not necessarily a good way to do programmatic, user-specific customization, for just the reason that you've found.
For that, I'd use the Preferences API.
I do the following method:-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With