Thursday, June 26, 2014

(J2EE) Load properties file once

Lesson learned:
package com.blogspot.codingineverydaylife;

import java.io.InputStream;
import java.util.Properties;

public class PropertiesUtil {
 private static final PropertiesUtil INSTANCE = new PropertiesUtil();
 public static Properties props = new Properties();
 static {  
  /*
   * If inStream is null it means that the properties file 
   * was not loaded. Make sure that the path you provided in the
   * getResourceAsStream() method is the path from the root of
   * the class loader. 
   */
  InputStream inStream = PropertiesUtil.class.getClassLoader()
    .getResourceAsStream("my.properties");
  try {
   if (inStream != null)
   {
    props.load(inStream);
    inStream.close();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 protected PropertiesUtil() {}
 public static PropertiesUtil getInstance() {
  return INSTANCE;
 }
 public String getProperty(String key) {
  return props.getProperty(key);
 }
}
The properties file should be in:


If you want the properties file to reside in, say, com.blogspot.codingineverydaylife.resources package, just specify in the getResourceAsStream() "com/blogspot/codingineverydaylife/resources/my.properties" and you should be good to go.

No comments: