Monday, March 3, 2008

properties file in java

Using properties file in java is pretty very common. But the same properties file gives lots of trouble while deployment. java.io.* is bit evil. absolute path makes code OS dependent, while relative path is dependent on JVM. Specially when one is working on app server, thing become much more difficult to trace and debug. i came across this cool coding tip for easy deployment.

/**********************************************************************/
String LOG_PROPERTIES_FILE = "Log4J.properties";
Properties logProperties = new Properties();
InputStream in = null;
ClassLoader loader = Thread.currentThread ().getContextClassLoader ();

try {
if (loader == null) loader = ClassLoader.getSystemClassLoader ();
in = loader.getResourceAsStream ("your/package/"+LOG_PROPERTIES_FILE);
if (in != null){
logProperties.load(in);
}
System.out.println("Loaded properties "+LOG_PROPERTIES_FILE);

} catch (IOException e) {
throw new RuntimeException("Unable to load logging property " +LOG_PROPERTIES_FILE);
}
/**********************************************************************/

instaed of using FileInputStream directly to read file from classpath, I used ClassLoader to get from current JVM's classpath. the properties file exists as part of same package. This resource file is read as InputStream and loaded in properties.