java修改properties文件内容(读取、修改、追加)

PropertiesConfiguration 是 Apache 帮我们实现按照文件的顺序读取properties文件的类,Properties类能做的它都能做。不仅如此,他还有许多方便实用的附加功能。

工具类:

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


public class PropertiesUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
    private static final String NATIVE_FILE_ADDRESS = "zta-monitor-api/src/main/resources/dev/statistics.properties";
    private static final String DEPLOY_FILE_ADDRESS = "export/App/conf/statistics.properties";

    public static void setValueToProperties(String key, String value) {
        try {
            PropertiesConfiguration propsConfig = new PropertiesConfiguration(DEPLOY_FILE_ADDRESS);
            propsConfig.setAutoSave(true);
            propsConfig.setProperty(key, value);
        } catch (Exception e) {
            logger.error("setValueToProperties error : {}", e.getMessage());
        }
    }

    public static void addValueToProperties(String key, String value) {
        try {
            PropertiesConfiguration propsConfig = new PropertiesConfiguration(DEPLOY_FILE_ADDRESS);
            // 修改属性之后自动保存,省去了propsConfig.save()过程
            propsConfig.setAutoSave(true);
            propsConfig.addProperty(key, value);
        } catch (Exception e) {
            logger.error("addValueToProperties error : {}", e.getMessage());
        }
    }


    public static String getValueFromProperties(String key) {
        String res = null;
        try {
            PropertiesConfiguration propsConfig = new PropertiesConfiguration(DEPLOY_FILE_ADDRESS);
            res = propsConfig.getString(key);
        } catch (Exception e) {
            logger.error("getValueFromProperties error : {}", e.getMessage());
        }
        return res;
    }

    public static void main(String[] args) {
        try {
            setValueToProperties("name2", "testError");
            addValueToProperties("name4", "test4");
            String name2 = getValueFromProperties("name4");
            System.out.println(name2);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

除此之外,还可以 propsConfig.setEncoding("utf-8") 设置编码。

需要的maven依赖:

  
    commons-configuration  
    commons-configuration  
    1.10  
  

你可能感兴趣的:(工具使用,java,java,开发语言)