Read property file from resource folder /directory in java (example)

  1. Given a property file defining the properties of a java application.
    • Property file will be residing in the resource folder/directory.
  2. Load the property file present in resource directory.
    1. Load property using Properties class in java.
    2. Properties class extends Hashtable. Hashtable will provide properties as key value pairs..
    3. We will iterate through key / value pairs of application’s properties.
  3. We will iterate through application’s properties & we will print all properties.

Program – read property file from resource directory in java (example)

package org.learn;

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

public class PropertyReader {

    public static void main(String[] args) throws IOException {
        readProperties();
    }

    private static void readProperties() throws IOException {
        InputStream inputStream = null;
        try {
            Properties properties = new Properties();
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            inputStream = loader.getResourceAsStream("project.properties");
            properties.load(inputStream);

            properties.forEach(
                             (key, value)
                                ->
                            System.out.println(
                                    key + "=" + value
                            )
                     );
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
}

Output – read property file from resource directory in java (example)

user.email=admin@gmail.com
user.country=USA
user.age=25
user.password=password
user.name=admin

Download code – read property file from resource directory java

Scroll to Top