Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Reading and Writing Configuration Files in Java

Tech 2

Loading Configuration Data

Configuration files can be accessed using the class loader to obtain an input stream directly:

username=admin
password=secret123
public class ConfigReader {
    public static void main(String[] args) throws IOException {
        ConfigReader app = new ConfigReader();
        InputStream configStream = app.getClass()
                                     .getClassLoader()
                                     .getResourceAsStream("app.config");
        
        Properties config = new Properties();
        config.load(configStream);
        
        System.out.println(config.getProperty("username"));
        System.out.println(config.getProperty("password"));
    }
}

Alternatively, file paths can be resolved first before opening streams:

public class ConfigReaderAlt {
    public static void main(String[] args) throws IOException {
        ConfigReaderAlt app = new ConfigReaderAlt();
        String configPath = app.getClass()
                              .getClassLoader()
                              .getResource("app.config")
                              .getPath();
        
        FileInputStream fileStream = new FileInputStream(configPath);
        Properties config = new Properties();
        config.load(fileStream);
        
        System.out.println(config.getProperty("username"));
        System.out.println(config.getProperty("password"));
    }
}

Modifying Configuration Values

To update configuration entries, use the setProperty method followed by storing changes:

config.setProperty("key", "value");
config.store(outputStream, null);

Compleet example for updating configurations:

Properties settings = loadConfig(filePath);
settings.setProperty("timeout", "30");

FileOutputStream output = null;
try {
    output = new FileOutputStream(
        Thread.currentThread()
               .getContextClassLoader()
               .getResource(filePath)
               .getPath()
    );
    settings.store(output, null);
} catch (IOException error) {
    error.printStackTrace();
} finally {
    if (output != null) {
        output.close();
    }
}

Utility Implementation

A reusable utility simplifies configuraiton management operations:

package com.example.utils;

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

public class PropertyManager {
    
    public static Properties loadFromFile(String filePath) {
        Properties props = new Properties();
        try {
            props.load(Thread.currentThread()
                           .getContextClassLoader()
                           .getResourceAsStream(filePath));
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return props;
    }
    
    public static String getValue(String filePath, String propertyKey) {
        Properties props = loadFromFile(filePath);
        return props.getProperty(propertyKey);
    }
    
    public static void updateValue(String filePath, String key, String newValue) {
        Properties props = loadFromFile(filePath);
        props.setProperty(key, newValue);
        
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(
                Thread.currentThread()
                       .getContextClassLoader()
                       .getResource(filePath)
                       .getPath()
            );
            props.store(fileOut, null);
        } catch (IOException exception) {
            exception.printStackTrace();
        } finally {
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException ignored) {}
            }
        }
    }
}

Example usage of the utility:

public static void main(String[] args) throws IOException {
    String currentValue = PropertyManager.getValue("application.settings", "mode");
    System.out.println(currentValue);
    
    PropertyManager.updateValue("application.settings", "mode", "production");
    
    String updatedValue = PropertyManager.getValue("application.settings", "mode");
    System.out.println(updatedValue);
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.