How to Read a Properties File in Java: Step-by-Step Explanation

📘 Reading a Properties File in Java

In Java, a properties file is commonly used to store configuration data such as database credentials in the form of key–value pairs. To read this file, Java provides the Properties class.

🧩 Steps to Read a Properties File

🔹 Step 1: Create a Properties Object

Create an object of the Properties class.
This object contains:
  • load() method
  • Overloaded getProperty() methods

Properties props = new Properties();

🔹 Step 2: Create a FileReader Object

Create an object of the FileReader class by passing the file path of the properties file.

FileReader fr = new FileReader("config.properties");
📌 When the FileReader object is created, the operating system opens an input stream to read the file.

🔹 Step 3: Load the Properties File

Use the load() method to read key–value pairs from the file and store them inside the Properties object.

props.load(fr);

🔹 Step 4: Read Values Using getProperty()

Use the getProperty() method to retrieve values using keys.

String value = props.getProperty("db.url");

⚠️ Important Behavior of getProperty()

  • If the key is valid, the associated value is returned
  • If the key is invalid, the method returns null

🌍 Real-Life Example

Reading a properties file is like checking saved settings on your phone:
If the setting exists → value is shown
If the setting does not exist → nothing is returned

Key Points to Remember

  • Properties file stores data as key = value
  • Properties class is in java.util package
  • FileReader opens the input stream
  • load() reads data into memory
  • getProperty() fetches values safely

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know