动态修改properties

本文介绍了如何在Java中动态修改properties文件。通过提供一个工具类,可以针对不同的properties文件创建对应的PropConfig对象,以实现单独修改的目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、工具类:

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;

public class Config {
    private static PropertiesConfiguration propConfig;

    private static final Config CONFIG = new Config();

    /**
     * 自动保存
     */
    private static boolean autoSave = true;

    private Config() {
    }

    public static Config getInstance(String propertiesFile) {
        //执行初始化
        init(propertiesFile);
        return CONFIG;
    }

    /**
     * 初始化
     *
     * @param propertiesFile
     * @throws ConfigurationException
     * @see
     */
    private static void init(String propertiesFile){
        try {
            propConfig = new PropertiesConfiguration(propertiesFile);
            //自动重新加载
            propConfig.setReloadingStrategy(new FileChangedReloadingStrategy());
            //自动保存
            propConfig.setAutoSave(autoSave);
        } catch (Exception  e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据Key获得对应的value
     *
     * @param key
     * @return
     * @see
     */
    public Object getValue(String key) {
        return propConfig.getProperty(key);
    }

    /**
     * 设置属性
     *
     * @param key
     * @param value
     * @see
     */
    public void setProperty(String key, String value) {
        propConfig.setProperty(key, value);
    }
}

2、使用

String initConfigurationWhetherPath = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/initConfiguration.properties");
Config initConfigurationWhetherCg = Config.getInstance(initConfigurationWhetherPath);
initConfigurationWhetherCg.setProperty("initConfigurationWhether","1");

*.properties:

initConfigurationWhether=0

用此工具类修改多个properties时,一个properties对应一个propConfig对象,故需重新getInstance,目的是修改propConfig对象:

Config initConfigurationWhetherCg = Config.getInstance(initConfigurationWhetherPath);
initConfigurationWhetherCg.setProperty("initConfigurationWhether","1");
String saveImageYNPath = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/drive.properties");
Config saveImageYNCg = Config.getInstance(saveImageYNPath);
saveImageYNCg.setProperty("alarm.saveImage.yesOrNot",saveImage);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值