The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
In Core Java, the Properties
class is a class that represents a persistent set of properties, which can be loaded from or saved to a stream. It extends the Hashtable
class and implements the Map
interface. The key and value of properties are both strings. It is often used for configuration settings in Java applications.
Some common methods of the Properties
class include:
setProperty(String key, String value)
: Sets the value of the property with the specified key.getProperty(String key)
: Gets the value of the property with the specified key.load(InputStream input)
: Reads a property list from the specified input stream.store(OutputStream output, String comments)
: Writes this property list to the specified output stream.
Here’s a simple example of using the Properties
class:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesExample {public static void main(String[] args) {
// Creating a Properties object
Properties properties = new Properties();
// Setting properties
properties.setProperty(“database.url”, “jdbc:mysql://localhost:3306/mydatabase”);
properties.setProperty(“database.username”, “user123”);
properties.setProperty(“database.password”, “password123”);
// Saving properties to a file
try (FileOutputStream output = new FileOutputStream(“config.properties”)) {
properties.store(output, “Database Configuration”);
} catch (IOException e) {
e.printStackTrace();
}
// Loading properties from a file
try (FileInputStream input = new FileInputStream(“config.properties”)) {
properties.load(input);
} catch (IOException e) {
e.printStackTrace();
}
// Getting a property value
String databaseUrl = properties.getProperty(“database.url”);
System.out.println(“Database URL: “ + databaseUrl);
}
}
In this example, properties are set, stored in a file (config.properties
), loaded from the file, and then a specific property value is retrieved.