0

I have a gradle task to read a properties file and modify one of the property.

task addVersion {
    File configPropFile = file(configFilePath)
    def configProperties = new Properties()
    configProperties.load(configPropFile.newDataInputStream())
    def versions = configProperties.getProperty('product.versions')
    if(!versions.contains("1.2")){
        configProperties.setProperty('product.versions', versions + ',' + "1.2")
    }
    configProperties.store(configPropFile.newWriter(), null)
}

This task successfully rewrites the properties file, but while rewriting it doesn't maintains the sequence in which the properties were read. Can someone help me out with the changes I need to make to maintain the sequence of the properties in the file?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
user1731553
  • 1,887
  • 5
  • 22
  • 33

1 Answers1

0

The java Properties class is unordered. This is nice in theory as it is supposed to keep a "set of properties" and thus not care about the ordering of the properties within the set.

It is not so nice in practice where you often run into scenarios where ordering matters such as checking files into source control and getting "false positive" changes caused by reordering of the properties within a properties file.

You can either write some custom code to iterate through the lines in the file and change that one line yourself or you can opt for using a custom class like the following:

https://github.com/etiennestuder/java-ordered-properties

which replaces the java properties class, does the sane thing and keeps ordering. The above github project also fixes another "feature" of the java properties persistence which is that it writes out the date into the properties file which, again, leads to false positive changes.

This has been disturbing me for some time. Glad somebody went ahead and wrote the above fix.

Matias Bjarland
  • 4,124
  • 1
  • 13
  • 21