简体   繁体   中英

Making changes in the properties file of Java project

I need to make a change in .properties file in my Java project. This is later deployed as a jar and used by other Java project. But according to this , I see that we should not directly make the change instead create a new object. Where should we create that new object and how can we make sure that its changes are visible?

Yes that's correct if your properties files is inside a jar then you won't be able to directly change that properties file since its packaged and zipped up in an archive. Instead you can create/change the file placed on a drive and read it, I used "user.home" for an example which you can change it as your need, below is the code for the same:

package com.test.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertyFileReader {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(PropertyFileReader.class);

    private static Properties properties;
    private static final String APPLICATION_PROPERTIES = "application.properties";
    private static final String workingDir = System.getProperty("user.home");
    private static File file = new File(workingDir, APPLICATION_PROPERTIES);
    static {
        properties = new Properties();
    }

    public static void main(String[] args) {
        write("hello", "2");
        System.out.println(read("hello"));
    }

    public static String read(final String propertyName) {
        try (InputStream input = new FileInputStream(file)) {
            properties.load(input);
        } catch (IOException ex) {
            LOGGER.error("Error occurred while reading property from file : ",
                    ex);
        }
        return properties.getProperty(propertyName);
    }

    public static void write(final String propertName,
            final String propertyValue) {
        try (OutputStream output = new FileOutputStream(file)) {
            properties.setProperty(propertName, propertyValue);
            properties.store(output, null);
        } catch (IOException io) {
            LOGGER.error("Error occurred while writing property to file : ", io);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM