The Properties Class
The java.util.Properties class is a subclass of Hashtable. It is used to maintain a persistent set of properties, where both the keys and the values are exclusively String objects.
The Properties class is extensively used in Java applications to manage configuration settings. Because it can be easily saved to a file and loaded from a file, it is ideal for storing database credentials, API keys, or application preferences without hardcoding them into your source code.
The .properties File Format
A typical properties file (e.g., config.properties) stores data as simple key-value pairs separated by an equals sign (=).
db.url=jdbc:mysql://localhost:3306/mydb
db.username=admin
db.password=secret123
app.version=1.4.2
1. Loading Properties from a File
To read a properties file, you create a Properties object, attach a FileReader or InputStream to your configuration file, and call the load() method. Once loaded, you retrieve the values using the getProperty(String key) method.
import java.io.FileReader;
import java.util.Properties;
public class LabProperties1 {
public static void main(String[] args) {
try {
// 1. Point the FileReader to the properties file
FileReader reader = new FileReader("config.properties");
// 2. Create the Properties object
Properties props = new Properties();
// 3. Load the data from the reader
props.load(reader);
// 4. Retrieve values using keys
System.out.println("Database URL: " + props.getProperty("db.url"));
System.out.println("Username: " + props.getProperty("db.username"));
// If a key doesn't exist, it returns null
System.out.println("Missing Key: " + props.getProperty("app.theme"));
} catch (Exception e) {
System.out.println("Error reading the properties file: " + e);
}
}
}
2. Saving Properties to a File
You can also create properties programmatically and save them to a file using the store() method. You set the key-value pairs using the setProperty(String key, String value) method.
import java.io.FileWriter;
import java.util.Properties;
public class LabProperties2 {
public static void main(String[] args) {
try {
// 1. Create a Properties object
Properties props = new Properties();
// 2. Set the key-value pairs
props.setProperty("user.name", "Midhun");
props.setProperty("user.email", "midhun@example.com");
props.setProperty("theme", "dark");
// 3. Point the FileWriter to the output file
FileWriter writer = new FileWriter("user_settings.properties");
// 4. Store the properties (with an optional comment string)
props.store(writer, "User Preference Settings");
System.out.println("Settings successfully saved!");
} catch (Exception e) {
System.out.println("Error saving properties: " + e);
}
}
}
[!NOTE] The
Propertiesclass is thread-safe (because it extends the synchronizedHashtable), meaning multiple threads can safely read and write configuration properties simultaneously.