In this guide, you will learn about the Properties store() method in Java programming and how to use it with an example.
1. Properties store() Method Overview
Definition:
The store() method of the Properties class in Java is used to write the property list (key-value pairs) to the specified output stream, accompanied by the specified comments. 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 stored to or loaded from a stream.
Syntax:
public void store(OutputStream out, String comments) throws IOException
public void store(Writer writer, String comments) throws IOException
Parameters:
- out: The output stream to write the property list to.
- writer: A character output stream.
- comments: A description of the property list or null if no comment should be added.
Key Points:
- The store() method is used to store properties to an output stream or a writer.
- It writes the properties in the form of key-value pairs.
- The method throws an IOException if writing to the specified output stream or writer fails.
- It’s commonly used to store properties in a file with the .properties extension, but they can also be stored to other types of streams.
- If the comments parameter is non-null, then a comment line is generated in the output.
2. Properties store() Method Example
import java.io.StringWriter;
import java.util.Properties;
public class PropertiesStoreExample {
public static void main(String[] args) {
try {
Properties properties = new Properties();
// Adding some properties
properties.setProperty("key1", "value1");
properties.setProperty("key2", "value2");
StringWriter writer = new StringWriter();
// Storing properties to a string using store() method with comments
properties.store(writer, "Sample Properties");
// Displaying the stored properties
System.out.println("Stored Properties: \n" + writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Stored Properties: #Sample Properties key1=value1 key2=value2
Explanation:
In this example, a Properties object is created, and a couple of properties are added to it. A StringWriter is initialized, and the store() method is then used to store these properties to the string writer with some comments. The output displays the stored properties, verifying that the properties have been successfully stored, and the comments are also included in the output.
Comments
Post a Comment
Leave Comment