Tuesday, February 11, 2014

How to Read Properties File in Java


This blog explains about how to read '.properties' file in Java

For eg : HostNamesURLS.properties file stores the values using key value pair

Below is the 'PropertyLoader' java class, which loads the all the properties into java.util.HashMap

       

  public class PropertyLoader {
   static PropertyLoader sPropertyLoader = null;
    static Properties propertyMap;
    public static PropertyLoader getInstance(){
        if(sPropertyLoader == null){
            sPropertyLoader = new PropertyLoader();
        }
        return sPropertyLoader;
    }
    
    private Properties loadProperties() {
        InputStream is;
        try {
            if (propertyMap == null) {
                propertyMap = new Properties();
                is =
        this.getClass().getClassLoader().getResourceAsStream("HostNameURLS.properties");
                propertyMap.load(is);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return propertyMap;
    }

    public void setPropertyMap(Properties pPropertyMap) {
        this.propertyMap = pPropertyMap;
    }
    public Properties getPropertyMap() {
        if(propertyMap == null){
            loadProperties();
        }
        return this.propertyMap;
    }    
}
  
       
 

Below is the sample code how to retrieve the values using above class

Object value = PropertyLoader.getInstance().getPropertyMap().get("key");

No comments:

Post a Comment