栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

yaml格式(yaml文件格式)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

yaml格式(yaml文件格式)

前言

我在遇到准备将一串符合yaml 的字符串进行解析,在搜索之后发现解析yaml 基本都是对文件进行解析。但自己字符串用 new Yaml().loadAs 无法解析,按道理也是支持字符串不应该不支持。想到自己字符串的换行可能不对,那么在java中如何才认为是一个换行呢?

BufferedWriter writer = new BufferedWriter(write);
writer.newline() 这样一个方法,看了这个实现方式

 String lineSeparator = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("line.separator")); 

这个是一个换行符, 通过这个看到换行符实际就是一个rn 但是又给自己拼接出来不一样。
效果就是

自己拼接出来rn ,如果是通过上面反复获取到换行符那就是真的换行了。那么有了上面理解就有下面一篇对字符串解析的工具类

实践
package com.yin.common.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import sun.security.action.GetPropertyAction;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.AccessController;
import java.util.Collections;
import java.util.linkedHashMap;
import java.util.Map;
import java.util.Objects;


public class YmlUtil {

    private static Logger logger = LoggerFactory.getLogger(YmlUtil.class);

    public static void main(String[] args) {
//        Map targetMap = parseYamlFile("D:\code\plugin_demo\web\src\main\resources\application.yml");
//        for (Map.Entry entry : targetMap.entrySet()) {
//            System.out.println(entry.getKey() + ":" + entry.getValue());
//        }

        StringBuilder ymlBuilder= new StringBuilder();
        try(  FileInputStream fileInputStream = new FileInputStream(new File("D:\code\plugin_demo\web\src\main\resources\application.yml"));
              InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
              BufferedReader bufferedReader=new BufferedReader(inputStreamReader)) {
            String lineStr = "";
            while ((lineStr = bufferedReader.readLine()) != null) {
                ymlBuilder.append(lineStr).append("\r\n");
            }
        }catch (Exception e) {
            logger.error("read fail", e);
        }
        System.out.println(ymlBuilder.toString());
        Map targetMap = parseYamlString(ymlBuilder.toString());
        for (Map.Entry entry : targetMap.entrySet()) {
           System.out.println(entry.getKey() + ":" + entry.getValue());
        }

    }

    
    public static Map parseYamlFile(String yamlFile){
        File file = new File(yamlFile);
        if (!file.exists()) {
            return Collections.EMPTY_MAP;
        }
        linkedHashMap sourceMap = null;
        try (FileInputStream fileInputStream = new FileInputStream(file);) {
            sourceMap= new Yaml().loadAs(fileInputStream
                    , linkedHashMap.class);
        } catch (Exception e) {
            logger.error("parseYamlFile fail", e);
        }
        if (Objects.isNull(sourceMap)) {
            return Collections.EMPTY_MAP;
        }
        linkedHashMap targetMap = new linkedHashMap<>(sourceMap.size());
        fillAllPathMap(sourceMap, targetMap, "");
        return targetMap;
    }

    
    public static Map parseYamlString(String yaml){
        String lineSeparator = AccessController.doPrivileged(
                new GetPropertyAction("line.separator"));
        yaml = yaml.replace("\r", "");
        yaml = yaml.replace("\n", lineSeparator);
        linkedHashMap sourceMap = null;
        try {
            sourceMap = new Yaml().loadAs(yaml, linkedHashMap.class);
        } catch (Exception e) {
            logger.error("parseYamlString fail", e);
        }

        if (Objects.isNull(sourceMap)) {
            return Collections.EMPTY_MAP;
        }
        linkedHashMap targetMap = new linkedHashMap<>(sourceMap.size());
        fillAllPathMap(sourceMap, targetMap, "");
        return targetMap;
    }

    
    private static  void fillAllPathMap(Map sourceMap,Map targetMap,String prefix){
        prefix = StringUtils.isEmpty(prefix) ? prefix : prefix + ".";
        for (Map.Entry entry : sourceMap.entrySet()) {
            Object value = entry.getValue();
            if(Objects.nonNull(value) && (value instanceof Map)){
                fillAllPathMap((Map) value, targetMap, prefix+entry.getKey());
            }else{
                targetMap.put(prefix+entry.getKey(), value);
            }
        }
    }


}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/773357.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号