读写本地属性文件

读写本地属性文件

package com.abc.utils;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertiesUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static final String GLOBAL_CONFIG_FILE = "props/common.properties";
    private static PropertiesConfiguration configuration;

    static {
        try {
            configuration = new PropertiesConfiguration(GLOBAL_CONFIG_FILE);
            //自动重新加载
            configuration.setReloadingStrategy(new FileChangedReloadingStrategy());
            //自动保存
            configuration.setAutoSave(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getString(String key) {
        try {
            //中文需要转码 ISO-8859-1  => UTF-8
            return configuration.getString(key);
        } catch (Exception e) {
            logger.error("PropertiesUtil | method=getString() is error, error_msg:{}, error_info:{}", e.getMessage(), e);
        }
        return null;
    }

    public static int getInt(String key){
        try {
            return configuration.getInt(key);
        } catch (Exception e) {
            logger.error("PropertiesUtil | method=getInt() is error, error_msg:{}, error_info:{}", e.getMessage(), e);
        }
        return 0;
    }

    public static boolean getBoolean(String key){
        try {
            return configuration.getBoolean(key);
        } catch (Exception e) {
            logger.error("PropertiesUtil | method=getBoolean() is error, error_msg:{}, error_info:{}", e.getMessage(), e);
        }
        return false;
    }

    public static boolean setProperty(String key, Object value) {
        try {
            //中文需要转码 UTF-8  => ISO-8859-1
            configuration.setProperty(key, value);
            return true;
        } catch (Exception e) {
            logger.error("PropertiesUtil | method=setProperty() is error, error_msg:{}, error_info:{}", e.getMessage(), e);
        }
        return false;
    }

}

Maven配置如下:

<dependency>
   <groupId>commons-configuration</groupId>
    <artifactId>commons-configuration</artifactId>
    <version>${commons.configuration.version}</version>
</dependency>
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>${commons.beanutils.version}</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值