Wednesday, January 16, 2013

PropertiesConfiguration - update properties without deleting commented lines and preserving layout

The Properties class provided by java does not provide fancy methods to manage the existing layout and leaving the comments in the properties while when we read and update properties from java program. The comments will be deleted and the layout is not guaranteed.  Apache commons PropertiesConfiguration provides a facility that java.util.Properties does not provide; it helps to maintain the layout and preserve the comments in the properties file. Hence it is safe to update your properties file without corrupting the existing layout.

The following code will read properties file, remove few properties and save it. 
public void refineProperties(String propFilename) {
try {
PropertiesConfiguration props = new PropertiesConfiguration(propFilename);
Iterator it = props.getKeys();
while(it.hasNext()) {
String propName = it.next();
if("
jdbc.connection".equals(propName)) {
props.clearProperty(miss);
}
}
props.save();
} catch (ConfigurationException e) {
e.printStackTrace();
}
Input properties:-
#Properties for my envt
include = common.propertes
#Connection specific properties
jdbc.connection = NONE
jdbc.userid = tom
jdbc.password = tiger

After cleanup:-
The properties file still has the comments and the same layout as the input
#Properties for my envt
include = common.propertes
#Connection specific properties
jdbc.userid = tom
jdbc.password = tiger