Read values from a Property file using Java

Property file is a special type of file having .properties extension.

This file can be used to store configuration related data such as URL of the application, username, password. In this file, data is stored in Key-Value pair.

The format of storing data in the property file is keyName=value e.g. username=admin.

Sample property file is given as below:

username=admin
password=admin
environment=test

Now, in this blogpost, we are going to read the details (parameters) from the property file.

We will use certain classes and methods like Properties and InputStream provided in Java’s UTIL and IO packages.

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

public class ReadPropertyFile {
            public static void main(String[] args) {

            Properties prop = new Properties();
            InputStream input = null;

            try {

                     input = new FileInputStream(“config.properties”);

                    // load a property file
                    prop.load(input);

                   // fetch values of properties
                   System.out.println(prop.getProperty(“username”));
                   System.out.println(prop.getProperty(“password”));
                   System.out.println(prop.getProperty(“environment”));

             } catch (IOException ex) {
                   ex.printStackTrace();
             } finally {
                  if (input != null) {
                 try {
                         input.close();
                  } catch (IOException e) {
                        e.printStackTrace();
                 }
             }
        }

     }
}

Important methods :

load command :

Usage : Used to read the property file (key-value pairs) from the input stream.

Syntax : void load (InputStream inputStream)

Return type : void (Nothing)

Parameters : InputStream reference

getProperty command :

Usage : Used to get the value of passed Key from the loaded property file.

Syntax : String getProperty(String key)

Return type : String (value of key)

Parameters : String (key/ parameter name in Properties file)

 

Code Explanation:

input = new FileInputStream(“config.properties”);

The above line tries to access the Property file using FileInputStream.

prop.load(input);

The above line loads a property file using load() method of Properties class, by passing inputStream object, which holds property file.

System.out.println(prop.getProperty(“username”));

The above line gets a particular property’s values using getProperty(String propertyName) method of Properties class, by passing the particulat property’s name (key).

Hope it helps you!!

Cheers 🙂

 

Advertisements

#read-data-from-property-file, #read-property-file-using-java, #read-values-from-property-file