0

I am able to write to a Java .properties file successfully with this code:

Properties prop = new Properties();
prop.load(input);
prop.setProperty("myProp", "myValue");
prop.store(output, "");

But then when I look into my .properties file, all the structure is gone! The fields are written in random order, and all the comments (that took me a lot of effort to write) have been overwritten with nothing!

How can I write to a .properties file while making sure that its structure is conserved?

user5123481566
  • 53
  • 1
  • 10
  • Maybe [this](https://stackoverflow.com/questions/21337732/java-properties-file-appending-new-values) can help you? – J.F. Nov 10 '20 at 08:17
  • 5
    Don't ever re-write a file you wrote by hand without having a backup or at least source control. – Renato Nov 10 '20 at 08:26
  • @Renato Agreed. Which is why I have both. – user5123481566 Nov 10 '20 at 08:29
  • 1
    For writing them in order, see also [How can I write Java properties in a defined order?](https://stackoverflow.com/questions/17011108/how-can-i-write-java-properties-in-a-defined-order). – Raedwald Dec 01 '20 at 21:38
  • 1
    Please include a sample properties file in your question and also to explain where you wish a new, previously non-existing property to go, e.g. to the end of the file. In any case, out of the box comments are being discarded when reading a properties file. The `Properties` class does not have any fields or setter/getter methods for comments, so the behaviour is to be expected. The only comment you are able to write is a header comment for the whole file which in your sample code you set to an empty string. You will have to extend the class by an enhanced implementation. – kriegaex Dec 03 '20 at 03:32

1 Answers1

1

You can use Apache Commons Configuration 2:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-configuration2</artifactId>
  <version>2.1.1</version>
</dependency>

Input file demo.properties:

# This is the file header
#
# Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
# aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

# Database user
db.user=admin

# Database password
db.password=password

# Database URL
db.url=localhost

# This is the file footer
#
# Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
# occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Demo application reading, modifying and writing a new properties file:

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.PropertiesConfigurationLayout;
import org.apache.commons.configuration2.ex.ConfigurationException;

import java.io.*;

class PropertiesFileWithCommentsDemo {
  public static void main(String[] args) throws IOException, ConfigurationException {
    // Load existing properties file
    File file = new File("demo.properties");
    PropertiesConfiguration config = new PropertiesConfiguration();
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout();
    layout.load(config, new InputStreamReader(new FileInputStream(file)));

    // Print some information from the properties file
    System.out.println(layout.getHeaderComment());
    System.out.println(layout.getKeys());
    System.out.println(layout.getFooterComment());

    // Change existing property
    config.setProperty("db.password", "secret");

    // Add new property + comment + leading blank line
    config.setProperty("new.property", "Hello world!");
    layout.setComment("new.property", "This is a newly added property");
    layout.setBlancLinesBefore("new.property", 1);

    // Save to new properties file
    layout.save(config, new FileWriter("demo-append.properties", false));
  }
}

Console log:

# This is the file header
#
# Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
# aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
[db.user, db.password, db.url]

# This is the file footer
#
# Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
# occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Output file demo-append.properties:

# This is the file header
#
# Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
# aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

# Database user
db.user=admin

# Database password
db.password=secret

# Database URL
db.url=localhost

# This is a newly added property
new.property = Hello world!

# This is the file footer
#
# Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
# occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
kriegaex
  • 63,017
  • 15
  • 111
  • 202