java读取properties文件并修改、新增属性值

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取properties文件,修改文件内容
 * @author lixingh
 */
@Slf4j
public class PropertyModifyUtil extends Thread{
    
    private static Properties properties;
    //文件绝对路径
    private static final String propertiesUrl = "C:/Users/Administrator/Desktop/sysConfig.properties";
    private static String propertiesName;
    static {
        String[] urlArr = propertiesUrl.split("/");
        propertiesName = urlArr[urlArr.length-1];
    }
    
    /**
     * 加载文件
     * @throws IOException
     */
    public static void load() throws IOException{
        properties= new Properties();
        try(FileInputStream fis = new FileInputStream(propertiesUrl)){
            properties.load(fis);
        }
    }
    
    /**
     * 操作文件
     * @param key
     * @param value
     * @return
     */
    public static Boolean optionProperty(String key,String value){
        try (FileOutputStream fos = new FileOutputStream(propertiesUrl)){
            if(properties == null){
                load();
            }
            properties.setProperty(key, value);   
            // 将Properties集合保存到流中   
            properties.store(fos, "Copyright (c) Boxcode Studio");   
        } catch (IOException e) {  
            log.error(propertiesName+" load failed",e);
            return false;
        }
        return true;  
    }  
    
    /**
     * 修改
     * @param key
     * @param value
     * @return
     */
    public static Boolean updateProperty(String key,String value) {
        if(getProperty(key) == null) {
            log.info(propertiesName+" does not have this key");
            return false;
        }
        return optionProperty(key,value);
    }
    
    /**
     * 新增
     * @param key
     * @param value
     * @return
     */
    public static Boolean addProperty(String key,String value) {
        if(getProperty(key) != null) {
            log.info(propertiesName+" already has this key");
            return false;
        }
        return optionProperty(key,value);
    }
    
    /**
     * 获取属性值  
     * @param key
     * @return
     */
    public static String getProperty(String key){  
        try (FileInputStream fis = new FileInputStream(propertiesUrl)) {
            if(properties == null){
                load();
            }
            properties.load(fis);   
        } catch (IOException e) {  
            log.error(propertiesName+" load failed",e);
            return null;
        }   
        return properties.getProperty(key);  
    }
    
}

 

你可能感兴趣的:(java)