How to load Properties files in Java

This tutorial shows how to load PropertiesFiles in Java. To run the code, follow theses steps:

1 Create the file PropertiesFileLoading.properties:

city.name=San Francisco
city.state=California

2 Create the java code in PropertiesFileLoading.java:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
public class PropertiesFileLoading {
    public Properties load(String filename) {
        // Create the Object to return
        Properties properties = new Properties();
        try {
            // Load the Object from the file
            properties.load(new FileInputStream(filename));
        } catch (IOException e) {
            System.out.println("Error reading file " + filename);
            e.printStackTrace();
            return null;
        }
        return properties;
    }
    public void show(Properties props) {
        // Get all the keys from the properties
        Enumeration<Object> keys = props.keys();
        // Loop on the keys
        while (keys.hasMoreElements()) {
            String key = "" + keys.nextElement();
            // Write the key and the value
            System.out.println(key + " is " + props.getProperty(key));
        }
    }
    public static void main(String[] argv) {
        PropertiesFileLoading example = new PropertiesFileLoading();
        // Load properties file.
        Properties properties = example
                .load("PropertiesFileLoading.properties");
        // Show the properties
        example.show(properties);
    }
}

The output will be:

city.state is California
city.name is San Francisco

References:

Java 6 Collections

Recent Comments