Java Properties File: How to Read Configuration Properties
A Properties file in Java is a simple text file used to store configuration data in the form of key-value pairs. This allows you to separate configuration from code, making your application more flexible and easier to maintain.
Java में Properties file एक साधारण text file होती है जिसमें configuration data को key-value pairs के रूप में store किया जाता है। इससे configuration और code अलग हो जाता है, जिससे application maintain करना आसान हो जाता है।
Properties File Format
The properties file contains entries like key=value
. For example:
Properties file में entries इस तरह होती हैं: key=value
. उदाहरण के लिए:
app.name=My Java App
app.version=1.0
db.user=root
db.password=admin123
Save this as config.properties
file in your project folder.
इसे config.properties
नाम से अपने project folder में save करें।
Java Code to Read Properties File
The following Java code uses the Properties
class to load the config.properties
file and read values by key.
नीचे दिया गया Java code Properties
class का उपयोग करके config.properties
file को load करता है और key के आधार पर values पढ़ता है।
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class ReadProperties {
public static void main(String[] args) {
try {
// Create a Properties object
Properties props = new Properties();
// Load properties file
FileReader reader = new FileReader("config.properties");
props.load(reader);
// Read values by key
String appName = props.getProperty("app.name");
String version = props.getProperty("app.version");
String user = props.getProperty("db.user");
String password = props.getProperty("db.password");
// Print values
System.out.println("App Name: " + appName);
System.out.println("Version: " + version);
System.out.println("User: " + user);
System.out.println("Password: " + password);
} catch (IOException e) {
System.out.println("Error reading file.");
e.printStackTrace();
}
}
}
Output
App Name: My Java App Version: 1.0 User: root Password: admin123
Final Tips for Using Properties Files
- Properties files help separate configuration from code, improving maintainability.
- Use meaningful keys for better readability (e.g.,
app.name
,db.user
). - Always handle exceptions while reading the file to avoid runtime errors.
- Protect sensitive data such as passwords; consider encrypting or securing the properties file.
- Properties files से configuration और code अलग होता है, जिससे maintain करना आसान होता है।
- साफ़ और समझने योग्य keys का प्रयोग करें जैसे
app.name
,db.user
। - File पढ़ते समय exceptions को handle करना ज़रूरी है ताकि runtime errors न हों।
- संवेदनशील data जैसे passwords को सुरक्षित रखें; properties file को encrypt या secure करें।