Using properties file in java application

Properties files are a cool place to store your configuration details like database connection properties, error messages and other configurations for your program.

You can use properties file in your application using following utility class. This class basically loads your properties file on first attempt to access any property on further attempts to access any property it will return properties already loaded in memory and not attempt to read file again and again.

Static getProperty(String key) method allows you to get property value by passing the key and static method Set<Object> getkeys() returns a set of keys in the file.

package com.bharat.utils;

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

public class PropertiesUtil
{

  private static Properties props;

  static
  {
    props = new Properties();
    try
    {
      PropertiesUtil util = new PropertiesUtil();
      props = util.getPropertiesFromClasspath("placeholder.properties");
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

  // private constructor
  private PropertiesUtil()
  {
  }

  public static String getProperty(String key)
  {
    return props.getProperty(key);
  }

  public static Set<Object> getkeys()
  {
    return props.keySet();
  }

  public static Properties getProperties()
  {
    return props;
  }

  /**
   * loads properties file from classpath
   *
   * @param propFileName
   * @return
   * @throws IOException
   */
  private Properties getPropertiesFromClasspath(String propFileName)
                                                                    throws IOException
  {
    Properties props = new Properties();
    InputStream inputStream = null;
    try
    {
      inputStream =
          this.getClass().getClassLoader().getResourceAsStream(propFileName);

      if (inputStream == null)
      {
        throw new FileNotFoundException("property file '" + propFileName
            + "' not found in the classpath");
      }
      props.load(inputStream);
    }
    finally
    {
      inputStream.close();
    }
    return props;
  }
}


You may put your properties file anywhere in project’s classpath.

References:

http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html

Advertisements

, , , , ,

  1. #1 by Levan on September 16, 2012 - 12:23 pm

    Thank you for the example.

  2. #2 by Andy on February 4, 2013 - 12:25 pm

    Can you please give an example of main method .. where above code is used to access properties ..

    • #3 by Bharat Sharma on February 4, 2013 - 12:44 pm

      Hi Andy,
      Assuming that you have a maven project structure and a properties file named placeholder.properties put in your src/main/resources directory.

      put a message in your placeholder.properties file as below
      errorMsg=This is a an error message.

      now your main method can be as simple as this.

      package com.bharat.test;
      
      public class UsingPropertiesFileUtil 
      {
      	public static void main(String[] args) 
      	{
      		String errorMsg = PropertiesUtil.getProperty("errorMsg");
      		System.out.println(errorMsg);
      	}
      }
      

      and you should get the value string you put in your properties file on your console.

  3. #4 by s k sharma on June 15, 2013 - 3:58 am

    thanks great example !!

  4. #5 by Aravindan Chockalingam on August 2, 2013 - 8:35 pm

    Hi, Thanks for the article. Incase of multiple property files, is it better to have multiple class or to have properties file parameterized in above example? Thanks again

  5. #6 by puneetkagarwal on September 20, 2013 - 6:10 am

    Hello bharat,

    First of all appreciate ur efforts.This example really helped me to understand the concept.
    I have question with this.
    We have property file in which we have an entry :

    subject : data has been loaded for {0} on date {1}

    these are place holders where we want to place a value at run time.
    Is there any direct way using property object to place values rather then using String replace function.

    • #7 by Bharat Sharma on September 24, 2013 - 4:19 pm

      Hi Puneet,

      I don’t think there is something out of the box. but you may modify the utility as shown below. also to add to what is below you may also verify the count of parameters passed to the number of placeholders in the properties file and throw some runtime exception if count does not match.

      package com.bharat.utils;
       
      import java.io.FileNotFoundException;
      import java.io.IOException;
      import java.io.InputStream;
      import java.util.Properties;
      import java.util.Set;
       
      public class PropertiesUtil
      {
       
        private static Properties props;
        private static final String START_TOKEN = "{";
        private static final String END_TOKEN = "}";
        
        static
        {
          props = new Properties();
          try
          {
            PropertiesUtil util = new PropertiesUtil();
            props = util.getPropertiesFromClasspath("placeholder.properties");
          }
          catch (FileNotFoundException e)
          {
            e.printStackTrace();
          }
          catch (IOException e)
          {
            e.printStackTrace();
          }
        }
       
        // private constructor
        private PropertiesUtil()
        {
        }
       
        public static String getProperty(String key)
        {
          return props.getProperty(key);
        }
       
        public static String getProperty(String key, Object[] args)
        {
      	String value = props.getProperty(key);
      	if(value != null)
      	{
      		int index = 0;
      		for(Object arg : args)
      		{
      			String token = START_TOKEN + String.valueOf(index) + END_TOKEN; 
      			value = value.replace(token, String.valueOf(arg));
      			index ++;
      		}
      	}
          return value;
        }
          
        public static Set<Object> getkeys()
        {
          return props.keySet();
        }
       
        /**
         * loads properties file from classpath
         * 
         * @param propFileName
         * @return
         * @throws IOException
         */
        private Properties getPropertiesFromClasspath(String propFileName)
                                                                          throws IOException
        {
          Properties props = new Properties();
          InputStream inputStream =
              this.getClass().getClassLoader().getResourceAsStream(propFileName);
       
          if (inputStream == null)
          {
            throw new FileNotFoundException("property file '" + propFileName
                + "' not found in the classpath");
          }
       
          props.load(inputStream);
          return props;
        }
      }
      

      Usage

      String msg = PropertiesUtil.getProperty("test1", new Object[] {"111","222"});
      
  6. #8 by kamalesh on January 28, 2015 - 2:07 am

    great example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: