Sunday, 28 June 2015

Loading property file in java

Loading property file in java code.

Loading property file can be used for following purposes :
i) If you want to configure a value which need to be accessed by your code, then its easy to define in property file and easily configurable.
ii) log4j.property file is also required to pick sometimes if you need sepearate logging mechanism.

Following is the general code to pick property file :

package com.test.timer.utils;

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


public class PropertyUtils {
//protected static final Logger LOGGER   = LogFactory.getLogger(PropertyUtils.class);
private static Properties prop = null;

public static void init(){

//LOGGER.info("PropertyUtils.init called");
InputStream timerPropertiesIS = null;
try {
timerPropertiesIS = new FileInputStream(TimeEJBConstants.PROPERTIES_FILE_NAME);

} catch (FileNotFoundException e) {
//LOGGER.info("FileNotFoundException",e);
}

// props for logger
prop = new Properties();
try {
prop.load(timerPropertiesIS);
//LOGGER.info("Property file "+TimeEJBConstants.PROPERTIES_FILE_NAME+" loaded ");
} catch (IOException e) {
//LOGGER.info("FileNotFoundException",e);
}finally{
try {
timerPropertiesIS.close();
} catch (IOException e) {
//LOGGER.info("IOException",e);
}
}

}

public static String getProperty(String propName) {
return prop.getProperty(propName);
}

public static void init(Properties prop2) {
prop = prop2;

}

}

//Here,
TimeEJBConstants.PROPERTIES_FILE_NAME is name of property file present in domain path
like below :
public static final String PROPERTIES_FILE_NAME ="./CustomerTimer.properties";


Now, wherever you want to use the property file just call init() method 
PropertyUtils.init();
and use the variable defined in file as follows:
Integer.valueOf( PropertyUtils.getProperty(TimeEJBConstants.PRIORITY_Q_ONDEMAND));
for varaible :
public static final String PRIORITY_Q_ONDEMAND ="priority_On_Demand";


where varaible defined in CustomerTimer.properties is like
priority_On_Demand= 8

No comments:

Post a Comment