Correct Method to Update Property Values in Java Properties Files Without Deleting Others

Dec 05, 2025 · Programming · 9 views · 7.8

Keywords: Java | Properties_file_operation | try-with-resources

Abstract: This article provides an in-depth analysis of how to correctly update specific property values in .properties files in Java without deleting other contents. By dissecting common errors in the original code, such as opening input and output streams simultaneously causing file overwriting, it offers solutions using Java's core API with try-with-resources for proper resource management and mentions the alternative approach with Apache Commons Configuration library. Written in a technical paper style, the content includes code examples and practical recommendations to help readers learn efficient property file manipulation.

Problem Description

In Java development, .properties files are commonly used to store configuration information. When updating a specific property value, a frequent mistake is illustrated by the user's code: the user updates the country property from india to america, but the employed code results in other properties being deleted, leaving only the updated value. This can lead to data loss and system instability.

Analysis of the Issue

The core issue in the original code lies in the usage of input and output streams. In the code description, FileOutputStream and FileInputStream are opened simultaneously for the same file, causing the output stream to write from the beginning of the file and overwrite the original content. When props.store(out, null) is called, it only writes the current properties in the Properties object to the file. Since the input stream is closed or mishandled, the object only contains the loaded properties (or none due to incomplete handling), resulting in the loss of other properties. This highlights the importance of stream closing order in resource management.

Correct Solution Using Java Core API

Based on the best answer, using the try-with-resources pattern ensures that input and output streams are properly closed, avoiding file overwriting. Here is the revised code example:

import java.io.*;
import java.util.Properties;

public class UpdateProperty {
    public static void main(String args[]) throws Exception {
        Properties props = new Properties();
        // Use try-with-resources to auto-close the stream
        try (FileInputStream in = new FileInputStream("First.properties")) {
            props.load(in);
        }
        // After closing the input stream, update the property
        props.setProperty("country", "america");
        // Use try-with-resources again to open the output stream
        try (FileOutputStream out = new FileOutputStream("First.properties")) {
            props.store(out, null);
        }
    }
}

This code first loads the file content into the Properties object via FileInputStream and closes the input stream to prevent concurrent access issues. Then, it updates the country property using setProperty, and finally writes all properties back to the file with FileOutputStream. Since the input stream is closed, the output stream does not overwrite the original content but saves the complete updated property set. This method leverages the try-with-resources feature introduced in Java 7 and later, offering clean resource management.

Alternative Solution with Apache Commons Configuration

The supplementary answer mentions the Apache Commons Configuration library, which provides advanced features such as preserving comments and formatting in files. The approach using this library is as follows:

import org.apache.commons.configuration2.PropertiesConfiguration;

public class UpdatePropertyWithApache {
    public static void main(String[] args) throws Exception {
        PropertiesConfiguration conf = new PropertiesConfiguration("First.properties");
        conf.setProperty("country", "america");
        conf.save();
    }
}

This library manages stream operations internally, ensuring file integrity is maintained when updating specific properties, including comments and formatting. However, it requires an external library dependency, so consideration of project needs is necessary when opting for this solution.

Conclusion

When updating .properties files in Java, avoiding the deletion of other contents hinges on correctly managing the closure order of input and output streams. Using the try-with-resources pattern enables concise resource management, preventing file overwriting. For complex scenarios requiring file structure preservation, the Apache Commons Configuration library offers a robust alternative. Developers should choose the appropriate method based on specific requirements to enhance code reliability and maintainability. Through the provided code examples, this article aims to help readers understand and apply these methods to optimize their development work.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.