views:

716

answers:

3

Though java.util.properties allows reading and writing properties file, the writing does not preserve the formatting. Not surprising, because it is not tied to the property file.

Is there a PropertyFile class out there -- or some such -- that preserves comments and blank lines and updates property values in in place?

A: 

You can have a look to the Apache Commons Configuration, that contains PropertiesConfiguration class. However, as I have never used it, I don't know if it preserves the comments and formatting...

However, it worthes a try...

romaintaz
According to the docs, a "PropertiesConfigurationLayout" class will preserve formatting and comments.
Aaron Digulla
A: 

I once saw a class to do this with INI files but can't find the link anymore. If you can't find anything else, you can try DecentXML. I wrote this XML parser with the specific design goal to preserve the original formatting 100% (i.e. with comments, weird spaces in elements or around the root element, everything).

During parsing the resulting XML document, you just have to remember the elements which contain the value for your options and replace the text node in them. When you save, nothing untouched will change in any way.

Aaron Digulla
+5  A: 

It doesn't get much better than Apache's Commons Configuration API. This provides a unified approach to configuration from Property files, XML, JNDI, JDBC datasources, etc.

It's handling of property files is very good. It allows you to generate a PropertiesConfigurationLayout object from your property which preserves as much information about your property file as possible (whitespaces, comments etc). When you save changes to the property file, these will be preserved as best as possible.

Il-Bhima