Saturday, September 17, 2016

Java Program: Reading from properties file

Keeping the static configuration values in a separate file is always a good idea in terms of maintainability as we just need to open that file modify the configuration value directly rather than going through the code and modify the values manually.

Given below is a sample program which shows you how to use a properties file to store the configuration values and how to read it from Java program.

First I will show you the Java program to read the contents from properties file.

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

public class ReadFromPropertiesFile{

 public static void main (String args[]) {

  String propertyFileName = "configurationvalues.properties";
  Properties prop=new Properties();
  InputStream propertyFileStream = ReadFromPropertiesFile.class.getClassLoader().getResourceAsStream(propertyFileName);

  if (propertyFileStream != null) {

   try {
    prop.load(propertyFileStream );
   } catch (IOException ex) {
    ex.printStackTrace();
   }
   String username = prop.getProperty("username","");
   System.out.println("My username is :"+username);
  } else {

   System.out.println("Failed to read from properties file");

  }
 }
}

In this example,we have created a properties file named "configurationvalues.properties" with the below content.

username=prabheesh

Please note that properties file is nothing, but a text file which holds data in key-value format.
In the example shown above, the properties file is kept under the src directory where this java program is also present. (Note: We can keep the properties file anywhere we want, but we need to modify the classpath parameters to locate the properties file).

The above program will check whether the properties file is present in the classpath. If the file is present, the contents of the file will be read into a Properties object. Once the contents are loaded, we can display the values by passing the key information to getProperty() method.

No comments:

Post a Comment