【JAVA】YML转Properties工具类

目录

一、题述

二、源码


一、题述

博主需要在java代码中,将yml转成properties格式的map

但是在网上找了一圈,没找到一个稍微好点的轮子,于是自己写个工具类

二、源码

实现思路:先转嵌套map,再将map转成properties格式。

需要maven依赖包:

		
            org.yaml
            snakeyaml
            1.29
        

源码:


import com.alibaba.fastjson.JSONObject;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Title:
 * @Description:
 * @Author: xbl
 * @CreateDate: 2021/10/27 19:08
 */
public class YmlToProperties {

    public static void main(String[] args) {
        String path = "D:\\admin-entry\\src\\main\\resources\\application.yml";

        LinkedHashMap result = ymlToPorperties(path);

        System.out.println(new JSONObject(result));
    }

    public static LinkedHashMap ymlToPorperties(String path) {
        LinkedHashMap resultMap = null;
        Yaml yaml = new Yaml();
        FileInputStream in = null;
        try {
            in = new FileInputStream(path);
            LinkedHashMap m = yaml.load(in);
            resultMap = mapToPorperties(m);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultMap;
    }

    public static LinkedHashMap mapToPorperties(LinkedHashMap m) {
        final LinkedHashMap resultMap = new LinkedHashMap<>();
        mapToPorperties(null, resultMap, m);
        return resultMap;
    }

    private static void mapToPorperties(String key, final LinkedHashMap toMap, LinkedHashMap fromMap) {
        Iterator> it = fromMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = it.next();
            Object value = entry.getValue();
            if (value instanceof Map) {
                String relKey = entry.getKey();
                if (key != null) {
                    relKey = key + "." + entry.getKey();
                }
                mapToPorperties(relKey, toMap, (LinkedHashMap) value);
            } else {
                String relKey = entry.getKey();
                if (key != null) {
                    relKey = key + "." + entry.getKey();
                }
                toMap.put(relKey, entry.getValue());
            }
        }
    }

}

代码中的fast-json用于打印清晰数据,不需要可干掉。

简单的嵌套yml转换是ok的,复杂的yml理论上来说应该也ok,博主目前没试过,有需求可留言。

你可能感兴趣的:(Java,Tool,java,开发语言,后端)