Java Properties load()

In this guide, you will learn about the Properties load() method in Java programming and how to use it with an example.

1. Properties load() Method Overview

Definition:

The load() method of the Properties class in Java is used to read a property list (key and element pairs) from the input stream. This method is part of the java.util.Properties class, which is a subclass of Hashtable and represents a persistent set of properties that can be loaded from or saved to a stream.

Syntax:

public void load(InputStream inStream) throws IOException
public void load(Reader reader) throws IOException

Parameters:

- inStream: The input stream from which the properties are loaded.

- reader: A character input stream.

Key Points:

- The load() method is used to load properties from an input stream or a reader.

- It reads the properties in the form of key-value pairs.

- The method throws an IOException if reading from the specified input stream or reader fails.

- Any malformed Unicode escape sequences encountered in the input will cause an IllegalArgumentException to be thrown.

- The properties are usually stored in a file with the .properties extension, but they can also be loaded from other types of streams.

2. Properties load() Method Example

import java.io.StringReader;
import java.util.Properties;

public class PropertiesLoadExample {

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

            String propertiesString = "key1=value1\nkey2=value2";
            StringReader reader = new StringReader(propertiesString);

            // Loading properties from a string using load() method
            properties.load(reader);

            // Displaying the loaded properties
            System.out.println("Loaded Properties: " + properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Loaded Properties: {key1=value1, key2=value2}

Explanation:

In this example, a Properties object is created, and a StringReader is initialized with a string containing property key-value pairs. The load() method is then used to load these properties. The output displays the loaded properties, verifying that the properties have been successfully loaded into the Properties object from the given string.

Comments