Read Property File In Java

 Posted On  | Yashwant Chavan 

Welcome to another Java article series. Today we are going to learn about Java Properties class. And how it is used to load or read the .properties file data.

Basically properties file are used to store the data in the form of key and value pair. It used to store your application configuration details like database connection details, error messages, environment specific details. You can use any extension but .properties is most widely use as per my understanding. In below example I have define file which is located under "src/main/resources/" folder.

Java Properties Class API Details

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

A property list can contain another property list as its "defaults"; this second property list is searched if the property key is not found in the original property list.Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object.

Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a "compromised" Properties object that contains a non-String key.

Prints properties from file


import java.util.Properties;

public class ReadPropertyExample {
    public static void main(String[] args) {
        Properties properties = new Properties();

        try {
            properties.load(new FileInputStream("src/main/resources/"));
            System.out.println("Domain :- " + properties.getProperty("domain"));
            System.out.println("Website Age :- " + properties.getProperty("website_age"));
            System.out.println("Founder :- " + properties.getProperty("founder"));

            // Display all the values in the form of key value
            for (String key: properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                System.out.println("Key:- " + key + "Value:- " + value);

        } catch (IOException e) {
            System.out.println("Exception Occurred" + e.getMessage());


website_age=10 Months
founder=Yashwant Chavan

© 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0323 seconds.