目录
一、题述
二、源码
博主需要在java代码中,将yml转成properties格式的map
但是在网上找了一圈,没找到一个稍微好点的轮子,于是自己写个工具类
实现思路:先转嵌套map,再将map转成properties格式。
需要maven依赖包:
<dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>1.29</version></dependency>
源码:
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\l";LinkedHashMap<String, Object> result = ymlToPorperties(path);System.out.println(new JSONObject(result));}public static LinkedHashMap<String, Object> ymlToPorperties(String path) {LinkedHashMap<String, Object> resultMap = null;Yaml yaml = new Yaml();FileInputStream in = null;try {in = new FileInputStream(path);LinkedHashMap<String, Object> 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<String, Object> mapToPorperties(LinkedHashMap<String, Object> m) {final LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();mapToPorperties(null, resultMap, m);return resultMap;}private static void mapToPorperties(String key, final LinkedHashMap<String, Object> toMap, LinkedHashMap<String, Object> fromMap) {Iterator<Map.Entry<String, Object>> it = Set().iterator();while (it.hasNext()) {Map.Entry<String, Object> entry = it.next();Object value = Value();if (value instanceof Map) {String relKey = Key();if (key != null) {relKey = key + "." + Key();}mapToPorperties(relKey, toMap, (LinkedHashMap<String, Object>) value);} else {String relKey = Key();if (key != null) {relKey = key + "." + Key();}toMap.put(relKey, Value());}}}}
代码中的fast-json用于打印清晰数据,不需要可干掉。
简单的嵌套yml转换是ok的,复杂的yml理论上来说应该也ok,博主目前没试过,有需求可留言。
本文发布于:2024-01-28 20:32:51,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170644517510097.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |