Java Properties File Handling

Java Properties File Handling

In Java application development, managing configuration externally from the code is a best practice. It allows developers to tweak behavior without modifying the source code or redeploying applications. The Java Properties class, part of the java.util package, provides a simple mechanism to read and write key-value configuration pairs through .properties files.


1. What is a Properties File in Java?

A properties file is a plain text file with the .properties extension that contains configuration data as key-value pairs. It is commonly used for storing:

  • Application settings (name, version, logging level)

  • Database configuration (URL, user, password)

  • Localization and internationalization strings

Syntax Example

# Application Properties
app.name=MyJavaApp
app.version=1.0.2

# Database Configuration
db.url=jdbc:mysql://localhost:3306/sampledb
db.user=admin
db.password=secret

2. The Properties Class

Java provides the Properties class which extends Hashtable<Object,Object>. It is specifically designed for reading and writing .properties files.

Common Methods

  • load(InputStream inStream) — Loads key-value pairs from an input stream.

  • store(OutputStream out, String comments) — Writes key-value pairs to an output stream.

  • getProperty(String key) — Retrieves the value for a given key.

  • setProperty(String key, String value) — Sets the value for a key.


3. Reading Properties from a File

To load properties from a file:

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

public class PropertiesReader {
    public static void main(String[] args) {
        Properties prop = new Properties();

        try (FileInputStream fis = new FileInputStream("config.properties")) {
            prop.load(fis);

            System.out.println("App Name: " + prop.getProperty("app.name"));
            System.out.println("Version: " + prop.getProperty("app.version"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. Writing to a Properties File

To create or update a properties file programmatically:

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

public class PropertiesWriter {
    public static void main(String[] args) {
        Properties prop = new Properties();

        prop.setProperty("app.name", "UpdatedJavaApp");
        prop.setProperty("app.version", "1.1.0");

        try (FileOutputStream fos = new FileOutputStream("config.properties")) {
            prop.store(fos, "Application Configuration Updated");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5. Modifying Existing Properties

To read, update, and write back to the same properties file:

Properties prop = new Properties();
try (FileInputStream fis = new FileInputStream("config.properties")) {
    prop.load(fis);
}

prop.setProperty("app.version", "1.2.0");

try (FileOutputStream fos = new FileOutputStream("config.properties")) {
    prop.store(fos, "Updated App Version");
}

6. Default Properties

You can also define default values for keys using chained properties:

Properties defaultProps = new Properties();
defaultProps.setProperty("app.name", "DefaultApp");

Properties appProps = new Properties(defaultProps);
appProps.getProperty("app.name"); // Returns DefaultApp if not overridden

7. Internationalization Support: ResourceBundle

Java supports locale-sensitive resources through ResourceBundle, which can work with .properties files suffixed with locale codes.

Example:

  • messages_en.properties

  • messages_fr.properties

ResourceBundle bundle = ResourceBundle.getBundle("messages", Locale.FRANCE);
String greeting = bundle.getString("hello"); // Bonjour

8. Best Practices

  • Avoid sensitive data like passwords in plain properties files. Use environment variables or encrypted configurations instead.

  • Use try-with-resources for file handling to avoid memory leaks.

  • Use relative paths or classpath resources when deploying with JARs.

  • Separate environment configurations for dev, test, and production (e.g., config-dev.properties).


9. Alternative: Loading from Classpath

try (InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties")) {
    Properties prop = new Properties();
    prop.load(input);
} catch (IOException ex) {
    ex.printStackTrace();
}

This is useful when bundling properties with your application inside a JAR.


10. Summary

Task Method Used
Read properties load(InputStream)
Write properties store(OutputStream, desc)
Get value by key getProperty(String key)
Set value by key setProperty(String key, value)
Use defaults Constructor with defaults
Handle locales ResourceBundle

Conclusion

Java's properties file handling is a powerful yet simple mechanism for managing configurations externally. With the Properties class and its built-in methods, developers can create dynamic applications that adapt to various environments without code changes. Proper use of properties files leads to cleaner code, better maintenance, and enhanced portability.

Previous
Next Post »