Core Java

How to Modify Property Files in Java

Property files are commonly used in Java applications to manage configuration data. They store key-value pairs and are easy to read and modify programmatically. Let us delve into understanding the different ways Java modifies property files, ranging from basic file stream operations to advanced libraries like Apache Commons Configuration.

1. Introduction

Java provides several approaches to read, modify, and manage .properties files, which are commonly used for application configuration. Choosing the right method depends on your specific needs, such as simplicity, performance, or support for advanced features. The main techniques include:

  • Using the built-in java.util.Properties class along with standard file input/output streams, which offers a straightforward way to load and save key-value pairs in properties files
  • Leveraging Apache Commons Configuration, a powerful library that simplifies handling of hierarchical and complex configuration files, with additional features such as automatic reloads and validation
  • Using Java NIO’s Files API for more granular file manipulation, including reading and writing file lines directly. This method is useful when you want precise control over file contents without fully loading the properties into memory
  • Handling XML-based property files using Properties.storeToXML() and loadFromXML(), allowing you to maintain properties in XML format for better readability or compatibility

These varied methods enable flexible and efficient management of configuration files in Java applications, whether for simple use cases or complex, dynamic configurations.

2. Code Example

2.1 Creating the app.properties File

This section shows the creation of a simple properties file named app.properties. This file stores key-value pairs in plain text format, which can be read and modified using Java APIs.

app.name=MyApp
app.version=1.0

2.2 Creating the app.xml File

Here, we create an XML-based properties file named app.xml. This format stores properties within an XML structure, allowing more structured data representation and easier integration with XML tools.

<?xml version="1.0" encoding="UTF-8"?>
<properties>
    <entry key="app.name">MyApp</entry>
    <entry key="app.version">1.0</entry>
</properties>

2.3 Adding Apache Commons Configuration Dependency

To simplify property file manipulation, especially for complex cases, the Apache Commons Configuration library is useful. Add the following Maven dependency to your pom.xml to include it in your project.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-configuration2</artifactId>
    <version>2.9.0</version>
</dependency>

2.4 Java Code Example for Modifying Properties Using Multiple Approaches

This Java example demonstrates four different ways to modify property files programmatically:

  • Using standard Java FileInputStream and FileOutputStream with Properties
  • Using Apache Commons Configuration for easier and robust property handling
  • Using Java NIO Files API to read and rewrite file lines
  • Updating XML formatted properties using Properties.loadFromXML() and storeToXML()
package com.example;

import java.io.*;
import java.nio.file.*;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;

public class Main {

    public static void main(String[] args) {
        try {
            String propFile = "config/app.properties";
            String xmlFile = "config/app.xml";

            // 1. Modify using Java File Streams
            updateUsingJavaStreams(propFile, "app.name", "StreamApp");

            // 2. Modify using Apache Commons Configuration
            updateUsingApacheCommons(propFile, "app.version", "2.5");

            // 3. Modify using Java NIO Files API
            updateUsingJavaNio(propFile, "app.name", "NioApp");

            // 4. Modify XML property file
            updateXmlProperty(xmlFile, "app.version", "3.5");

            System.out.println("All updates were completed successfully.");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 1. Update property using Java File Streams
    public static void updateUsingJavaStreams(String filePath, String key, String value) throws IOException {
        Properties props = new Properties();

        // Load existing properties
        try (InputStream input = new FileInputStream(filePath)) {
            props.load(input);
        }

        // Set new value
        props.setProperty(key, value);

        // Store updated properties back to file
        try (OutputStream output = new FileOutputStream(filePath)) {
            props.store(output, "Updated using Java Streams");
        }

        System.out.println("Updated using Java Streams");
    }

    // 2. Update property using Apache Commons Configuration
    public static void updateUsingApacheCommons(String filePath, String key, String value) throws Exception {
        Configurations configs = new Configurations();

        // Load and modify using Apache Commons
        PropertiesConfiguration config = configs.properties(new File(filePath));
        config.setProperty(key, value);
        config.write(new FileWriter(filePath));  // Save changes

        System.out.println("Updated using Apache Commons Configuration");
    }

    // 3. Update property using Java NIO Files API
    public static void updateUsingJavaNio(String filePath, String key, String value) throws IOException {
        Path path = Paths.get(filePath);
        List<String> lines = Files.readAllLines(path);

        // Replace the line with the matching key
        List<String> modifiedLines = lines.stream()
                .map(line -> line.startsWith(key + "=") ? key + "=" + value : line)
                .collect(Collectors.toList());

        // Write updated content
        Files.write(path, modifiedLines, StandardOpenOption.TRUNCATE_EXISTING);

        System.out.println("Updated using Java NIO Files API");
    }

    // 4. Update property in XML format
    public static void updateXmlProperty(String xmlFilePath, String key, String value) throws IOException {
        Properties props = new Properties();

        // Load from XML
        try (InputStream input = new FileInputStream(xmlFilePath)) {
            props.loadFromXML(input);
        }

        // Modify property
        props.setProperty(key, value);

        // Store back as XML
        try (OutputStream output = new FileOutputStream(xmlFilePath)) {
            props.storeToXML(output, "Updated XML Property");
        }

        System.out.println("Updated XML property file");
    }
}

2.4.1 Code Explanation

This Java program demonstrates four different methods to modify property files. In the main method, it specifies two files: a standard properties file (app.properties) and an XML properties file (app.xml). It then sequentially updates these files using four approaches: first, it uses traditional Java file streams with the Properties class to load, update, and save properties in the plain text properties file; second, it leverages the Apache Commons Configuration library, which simplifies reading and writing properties with its PropertiesConfiguration class; third, it uses Java’s NIO Files API to read all lines from the properties file, replace the line with the matching key, and write the modified lines back, showcasing a more manual but flexible approach; lastly, it updates the XML property file by loading properties using loadFromXML, modifying the specified key, and saving changes back to XML with storeToXML. Throughout, each method prints a confirmation message upon successful update, and exceptions are caught and printed to assist debugging. This example highlights various ways to programmatically manage configuration properties in Java, covering both plain text and XML formats.

2.4.2 Code Output

The code when executed gives the following output:

Updated using Java Streams
Updated using Apache Commons Configuration
Updated using Java NIO Files API
Updated XML property file
All updates were completed successfully.

app.properties file content after updates:

app.name=NioApp
app.version=2.5

app.xml file content after updates:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>Updated XML Property</comment>
    <entry key="app.name">MyApp</entry>
    <entry key="app.version">3.5</entry>
</properties>

3. Conclusion

Managing property files is a crucial aspect of Java application configuration. Depending on your requirements, you can use Java File Streams for simple key-value updates, Apache Commons Configuration for more advanced and robust handling, Java NIO for precise file-level editing, and the built-in XML methods to work with XML-based property files. These techniques provide the flexibility to programmatically update properties across various scenarios, including CI/CD pipelines, dynamic configuration updates, or desktop applications.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button