How to read properties file in Java.

Reading properties file in Java is much easier than you might have thought. Following example illustrates one simple way of reading properties from a properties file.

Let’s say we need to read from myConfig.properties file.
The properties file has following entries.

Directory = C:/prodFiles/
NumberOfFiles = 25
Extension = java
Here is the class to read the values of these keys.

import java.util.Properties;
import java.io.*;
   public class ReadValues{
	private static final String PROP_FILE="myConfig.properties";
	public void readPropertiesFile(){
       try{
		InputStream is = ReadValues.class.getResourceAsStream(PROP_FILE);
		Properties prop = new Properties();
        prop.load(is);
		String directory = prop.getProperty("Directory");
        String numberOfFiles = prop.getProperty("NumberOfFiles");
		String  fileExtension = prop.getProperty("Extension");
        is.close();

	  /* code to use values read from the file*/
       }catch(Exception e){
         System.out.println("Failed to read from " + PROP_FILE + " file.");
       }
   }
  }

The code is quite simple and self explanatory. Let me know if you have any questions.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • StumbleUpon
  • Digg
  • del.icio.us
  • Reddit
  • Sphinn
  • blinkbits
  • NewsVine
  • Smarking

If you enjoyed this post, make sure you subscribe to my RSS feed!


Related Posts:

  • Import static elements for more readable Java code
  • Test your Java skills.
  • Three ways to find minimum and maximum values in a Java array.
  • How to validate email, SSN, phone number in Java using Regular expressions.
  • Java Utility for JDBC
  • 4 Responses

    1. Bret:

      Well done. I appreciate the fact that you didn’t assume everyone knew how to read in a properties file with Java. It’s a simple task but worth the post. Thanks.

      Bret’s last blog post..Windows XP to Remain Available Until 2010

      Posted on April 9th, 2008 at 3:34 am

    2. John Doe:

      Thanks!

      Posted on May 12th, 2008 at 9:13 am

    3. vivek kumar:

      hi coud u plz tell me where u put your .properties file

      Posted on June 11th, 2008 at 1:12 am

    4. Zaheer:

      Vivek, you can put your properties file in any directory as long as that directory is in your classpath. For e.g; if you save your properties file under C:\resources directory make sure that C:\resources is in your classpath. Or you can put your properties file in the same directory where you have your class file.

      Posted on June 11th, 2008 at 8:43 pm

    Leave a Reply