读取yml内容读取项目结构外的yml内容

读取yml内容读取项目结构外的yml内容,第1张

读取yml内容 / 读取项目结构外的yml内容
package cn.com.tiptop.outsyscheck.config;


import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import javax.sound.midi.Soundbank;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.linkedHashMap;
import java.util.Map;

@Slf4j
@Component
public class YamlConfigs {

    private final static DumperOptions OPTIONS = new DumperOptions();

    private org.slf4j.Logger log = LoggerFactory.getLogger(YamlConfigs.class);

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

    
    public Map getYamlToMap(String fileName){
        linkedHashMap yamls = new linkedHashMap<>();
        Yaml yaml = new Yaml();
        try {
            @Cleanup InputStream in = YamlConfigs.class.getClassLoader().getResourceAsStream(fileName);
            yamls = yaml.loadAs(in,linkedHashMap.class);
        }catch (Exception e){
            log.error("{} load failed !!!" , fileName);
        }
        return yamls;
    }

    
    public Object getValue(String key, Map 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)o);
            }else {
                return null;
            }
        }else {
            return o;
        }
    }

    
    public Map setValue(String key,Object value) {
        Map result = new linkedHashMap<>();
        String[] keys = key.split("[.]");
        int i = keys.length - 1;
        result.put(keys[i], value);
        if (i > 0) {
            return setValue(key.substring(0, key.lastIndexOf(".")), result);
        }
        return result;
    }

    public Map setValue(Map map, String key, Object value){

        String[] keys = key.split("\.");

        int len = keys.length;
        Map temp = map;
        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;
    }


    
    public boolean updateYaml(String key, @Nullable Object value, String yamlName){

        Map yamlToMap = this.getYamlToMap(yamlName);
        if(null == yamlToMap) {
            return false;
        }
        Object oldVal = this.getValue(key, yamlToMap);

        //未找到key 不修改
        if(null == oldVal){
            log.error("{} key is not found",key);
            return false;
        }
        //不是最小节点值,不修改
        if(oldVal instanceof Map){
            log.error("input key is not last node {}",key);
            return false;
        }

        //新旧值一样 不修改
        if(value.equals(oldVal)){
            log.info("newVal equals oldVal, newVal: {} , oldVal: {}",value,oldVal);
            return false;
        }

        Yaml yaml = new Yaml(OPTIONS);
        String path = this.getClass().getClassLoader().getResource(yamlName).getPath();
        try {
            Map resultMap = this.setValue(yamlToMap, key, value);
            if(resultMap != null){
                yaml.dump(this.setValue(yamlToMap,key,value),new FileWriter(path));
                return true;
            }else {
                return false;
            }
        }catch (Exception e){
            log.error("yaml file update failed !");
            log.error("msg : {} ",e.getMessage());
            log.error("cause : {} ",e.getCause());
        }
        return false;
    }

    
}

读取非resource下的yml或非项目结构下yml的方法:

先搞成文件,再强转成map,调用上面的函数.

        try (FileInputStream inputStream = new FileInputStream("D:\checkPro\config\application.yml")) {
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
            dumperOptions.setPrettyFlow(false);
            Yaml yaml = new Yaml(dumperOptions);
            Map load = (Map)yaml.load(inputStream);
            YamlConfigs yamlConfigs = new YamlConfigs();
           int value1= (int) yamlConfigs.getValue("server.port", load);
        } catch (IOException e) {
        }

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5638457.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存