Sunday, August 02, 2009

Accessing properties file in a java apps

Properties file is a simple text file. It contains a set of key-value pairs. Each key is associated with a key. We use properties file to store the configuration properties so that we dont need to touch the code again n again and recompile n run the entire app. just editing the properties file should be enough.

I used the following code to load properties from a properties file in J2EE application. Following code shows how to read the properties file and load the available properties into Java.Util.Properties Object.

/* Reading a properties file */

Properties props = new Properties();

//loading the properties from file into "props"
try{
props.load(new FileInputStream(fileName);
//filename should be a string. for ex, abc.properties
}
Catch(IOException e){
System.out.println("IO Exception occurres while accessing the properties file"+fileName);
}

"props" contains all the properties available in the file. i.e. key/value pairs. It simply ignores the comments, if any, available in the file.

Following code shows how to write the properties into a file.
try{
props.store(new FileOutputStream(fileName), null);
}
Catch(IOException e){
System.out.println("IO Exception while accessing the properties file"+fileName);
}

PROS: no use of third party libraries and is easy to read and write from the properties file.
CONS: With this way of reading and writing to the files, all your comments will show at the starting of the file and then shows up the properties. So the comments (if any specific to the property will be gone and all comments mess up at the top of the file)
When to use: I recommend this way to use when your properties file doesn't have any comments. i.e. your properties file just contains key value pairs.

To know more about Java.Util.Properties: Java.Util.Properties

In my next post, I will discuss the efficient way to edit the properties file without affecting the comments and order of the properties.

No comments:

Post a Comment

È