Monday, August 03, 2009

Accessing properties file for efficient read/write










In previous post, we did not use any third party libraries for accessing the properties file. Here, we will be using the apache commons configuration API. You have to download the jar file and add it to the classpath.

Reading from a properties file:

Use the following line of code if you just want to read the properties file.

Configuration config = new PropertiesConfiguration(propertiesFileName);

Then you need to use the various methods available to read the propeties. It has some flexible methods such as to get the string type of values, or integer or a list of values.

Detailed information about Configuration Interface can be found here: org.apache.commons.Configuration

Writing to a properties file:

You have to use the PropertiesConfiguration object to write to the properties file.

Detailed information about PropertiesConfiguration can be found here: org.apache.commons.configuration.PropertiesConfiguration

Use the following code:

PropertiesConfiguration config;
try{
config = new PropertiesConfiguration(propertiesFileName);
config.setProperty(propertyName, propertyValue); //to update properties
config.save(); //writes the changes to the file
}
Catch(ConfigurationException e){
System.out.println("Configuration exception");
}

When you write/update the properties this way,
1. properties order in the file doesn't change
2. comments stays the same

Other Uses: We can save a back up of the properties file using the following method.

config.save(backupFileName). //backupFileName is the name of the back up file to be created

Some useful info from apache website can be found here

No comments:

Post a Comment

È