What is a .properties file In Java

Java Fusion
2 min readJan 28, 2024
java fusion

In Java, a “properties file” is a file that stores configuration data in a key-value pair format. This file is commonly used for storing configuration settings for Java applications.

Properties files are typically simple text files with a .properties extension.

Here’s a basic example of a properties file. create a file named (config.properties)

# Database Configuration
database.url=jdbc:mysql://localhost:3306/mydatabase
database.username=test
database.password=password
port= 9000

# Server Configuration
server.host=127.0.0.1
server.port=8080

In Java, the Properties class is used to work with properties files. This class extends Hashtable and represents a persistent set of properties.

Here’s a simple example of how you might use the Properties class to read from a Properties file


import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesDemo {

public void dbConnection() {

Properties properties = new Properties();
FileInputStream fileInputStream = null;
try {

fileInputStream = new FileInputStream("config.properties");
properties.load(fileInputStream);

String url = properties.getProperty("database.url");
String username = properties.getProperty("database.username");
String password = properties.getProperty("database.password");
String port = properties.getProperty("port");
String serverHost = properties.getProperty("server.host");
String serverPort = properties.getProperty("server.port");

System.out.println("URL: " + url);
System.out.println("Username: " + username);
System.out.println("Password: " + password);
System.out.println("Port: " + port);
System.out.println("Server Host: " + serverHost);
System.out.println("Server Port: " + serverPort);


} catch (IOException ex) {
System.out.println(ex.getMessage());
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {
PropertiesDemo propertiesDemo = new PropertiesDemo();
propertiesDemo.dbConnection();
}
}

In this above example:

  1. We create a Properties object.
Properties properties = new Properties();

2. We load the properties from the config.properties file using the load() method.

3. We retrieve the values of specific properties using the getProperty() method.

4. We then print out the values of these properties.

What is the basic use of properties files?

Properties files are commonly used for storing configurations that may change over time, such as database connection settings, application settings, etc.

Properties files should always be created in the below path.

java fusion

Happy reading and exploring! Thank you.

--

--

Java Fusion

Java enthusiast crafting code with passion. enthusiastic about creating robust, scalable applications. Let's code, innovate, and build the future together!