Properties File in Java: Configuration, Reading Data, and Methods Explained

📘 Properties File in Java

A Properties file is a configuration file used to store application settings—most commonly database credentials—in the form of key-value pairs.
It helps separate configuration data from application logic, making the application easier to maintain and modify.

🔑 Format of a Properties File

Properties
db.url=jdbc:mysql://localhost:3306/testdb
db.username=root
db.password=admin

📦 Reading a Properties File in Java

To read data from a properties file, Java provides the Properties class, which is available in the java.util package.

Required Packages:

  • java.util
  • java.io

🧩 Steps to Read a Properties File

  • Create an object of the Properties class
  • Open the file using FileReader
  • Load the key-value pairs into the Properties object
  • Retrieve values using keys

🔧 Important Methods of Properties Class

🔹 load() Method

Used to load key-value pairs from a file into the Properties object.

void load(FileReader fr) throws IOException

📌 This method belongs to the Properties class.

🔹 getProperty() Methods

Used to retrieve values from the Properties object.

1️⃣ Basic Method

String getProperty(String key)
  • Returns the value if the key exists
  • Returns null if the key does not exist

2️⃣ Overloaded Method

String getProperty(String key, String defaultValue)
  • Returns the value if the key exists
  • Returns the default message if the key is invalid

⚠️ Exceptions During File Reading

While reading a properties file, the following exceptions may occur:
  • FileNotFoundException
  • IOException
These must be handled using try-catch or throws.

🌍 Real-Life Example

Think of a properties file like a settings page of an app:
  • Username → login ID
  • Password → security key
  • Server URL → backend address
You can change settings without modifying the app code.

Advantages of Using Properties File

  • Centralized configuration
  • Easy maintenance
  • Better security
  • Supports loose coupling

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