Tuesday, January 8, 2008

Read Property File from JAVA

In most causes we need to keep our configuration information in a property file. This will increase the usability as well as maintainability of a project. This program demonstrate how to read a Java property file and how to extract values from that.

Sample property file: [ myprop.properties ]

name=Jeorge
age=17
country=Sri Lanka
city=Colombo

/*
* Main.java
*
* Created on January 8, 2008, 1:55 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package blog2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
*
* @author eranga
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {

if(args.length != 1){
throw new Exception("Please provide property file name as a command line parameter !");
}

String propertyFile = args[0];
File configPropsFile = new File(propertyFile);

if(!configPropsFile.exists())
throw new Exception("The config file : " + propertyFile + " does not exist.");

Properties myProp = new Properties();

myProp.load(new FileInputStream(propertyFile));

// Access properties
String prop1 = myProp.getProperty("name");
}

}

2 comments:

Lakindu said...

Can u help me to read an XML file using java/c++?

Eranga Samararathna said...

Are you want to read xml property file from java ? In this cause you can use myProp.loadFromXML(new FileInputStream(propertyFile));