对yaml文件进行增删改查操作

对yaml文件进行增删改查操作

所需依赖

<dependency>
	<groupId>org.yaml</groupId>
	<artifactId>snakeyaml</artifactId>
	<version>1.27</version>
</dependency>

代码编写



import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

/**
* @author 少年白马醉春风
 * 对yaml或yml文件进行增删改查操作
 */
public class YamlUtil {


    /**
     *设置yaml读取方式为块读取
     */
    private static DumperOptions dumperOptions = new DumperOptions();
    static{
        //设置yaml读取方式为块读取
        dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
        dumperOptions.setPrettyFlow(false);
    }


    /**
     * 对yaml文件进行修改
     * @param paramKey
     * @param paramValue
     * @return
     */
    public static boolean updateYaml( String paramKey, Object paramValue,String path) {
        Yaml yaml = new Yaml(dumperOptions);
        Map<String,Object> map = new HashMap<>();
        try {
            //将yaml文件加载为map格式
            map = yaml.loadAs(new FileInputStream(path), Map.class);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        boolean flag = updateYaml(paramKey, paramValue, map, path, yaml);
        return flag;
    }



    /**
     * 修改yaml中属性的值
     * @param key      key是properties的方式: aaa.bbb.ccc (key不存在不修改)
     * @param value    新的属性值 (新属性值和旧属性值一样,不修改)
     * @param yamlToMap map结构
     * @param path 路径
     * @return true 修改成功,false 修改失败。
     */
    public static boolean updateYaml(String key, Object value, Map<String, Object> yamlToMap, String path, Yaml yaml) {
        Object oldVal = getValue(key, yamlToMap);
        //未找到key 不修改
        if (null == oldVal) {
            return false;
        }
        try {
            Map<String, Object> resultMap = setValue(yamlToMap, key, value);
            if (resultMap != null) {
                yaml.dump(resultMap, new FileWriter(path));
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            System.out.println("yaml file update failed !");
        }
        return false;
    }

    /**
     * key格式:aaa.bbb.ccc
     * 通过properties的方式获取yaml中的属性值
     *
     * @param key
     * @param yamlMap
     * @return
     */
    public static Object getValue(String key, Map<String, Object> yamlMap) {
        String[] keys = key.split("[.]");
        Object o = yamlMap.get(keys[0]);
        if (key.contains(".")) {
            if (o instanceof Map) {
                return getValue(key.substring(key.indexOf(".") + 1), (Map<String, Object>) o);
            } else {
                return null;
            }
        } else {
            return o;
        }
    }



    /**
     * 修改yaml中的属性值
     */
    public static Map<String, Object> setValue(Map<String, Object> map, String key, Object value) {
        String[] keys = key.split("\\.");

        int len = keys.length;
        Map temp = map;
        if (len == 1){
            temp.put(keys[0],value);
        }else {
            for (int i = 0; i < len - 1; i++) {
                if (temp.containsKey(keys[i])) {
                    temp = (Map) temp.get(keys[i]);
                } else {
                    return null;
                }
                if (i == len - 2) {
                    temp.put(keys[i + 1], value);
                }
            }
            for (int j = 0; j < len - 1; j++) {
                if (j == len - 1) {
                    map.put(keys[j], temp);
                }
            }
        }
        return map;
    }


    /**
     * 向yaml文件中添加相关的信息
     * @param key
     * @param value
     * @return
     * @throws FileNotFoundException
     */
    public static boolean insertYaml(String key,String value,String path) throws FileNotFoundException {
        Yaml yaml = new Yaml(dumperOptions);
        Map<String,Object> map = yaml.loadAs(new FileInputStream(path), Map.class);
        return  insertYaml(key,value,map,path);
    }


    /**
     * 进行信息的插入
     * @param key
     * @param value
     * @param yamlToMap
     * @param path
     * @return
     */
    public static boolean insertYaml(String key, Object value, Map<String, Object> yamlToMap, String path) {

        Yaml yaml = new Yaml(dumperOptions);
        String[] keys = key.split("\\.");

        int len = keys.length;
        Map temp = yamlToMap;

        for (int i = 0; i < len; i++) {
            if (temp.containsKey(keys[i])) {
                temp = (Map) temp.get(keys[i]);
            } else {
                //该处对yaml的层级需要有判断,可能有问题
                if(i + 2 == len){
                    Map<String, Object> newMap = new HashMap<>();
                    newMap.put(keys[len-1],value);
                    temp.put(keys[i],newMap);
                    break;
                }else {
                    temp.put(keys[i], value);
                    break;
                }
            }
        }
        try {
            yaml.dump(yamlToMap, new FileWriter(path));
        } catch (Exception e) {
            System.out.println("yaml file insert failed !");
            return false;
        }
        return true;
    }

}

你可能感兴趣的:(java,数据库,开发语言)