importorg.springframework.core.io.Resource;importorg.springframework.lang.NonNull;importorg.springframework.lang.Nullable;importorg.springframework.util.StringUtils;importorg.yaml.snakeyaml.Yaml;importorg.yaml.snakeyaml.reader.UnicodeReader;importjava.io.IOException;import java.util.*;public classYamlUtils {/*** 单个yaml文件处理
*@paramresource
*@return*@throwsIOException*/
public static Map yamlHandler(@NonNull Resource resource) throwsIOException {//返回的结果
Map result = new LinkedHashMap<>();//读取方式
UnicodeReader reader = newUnicodeReader(resource.getInputStream());//单文件处理
Yaml yaml = newYaml();
Object object=yaml.load(reader);//这里只是简单处理,需要多个方式可以自己添加
if (object instanceofMap) {
Map map=(Map) object;
buildFlattenedMap(result, map,null);
}
reader.close();returnresult;
}/*** 单个yaml文件处理
*@paramresources
*@return*@throwsIOException*/
public static Map yamlHandler(@NonNull Resource[] resources) throwsIOException {//返回的结果
Map result = new LinkedHashMap<>();
Yaml yaml= newYaml();//多个文件处理
Iterator iterator =Arrays.stream(resources).iterator();while(iterator.hasNext()) {
Resource resource=iterator.next();
UnicodeReader reader= newUnicodeReader(resource.getInputStream());
Object object=yaml.load(reader);//这里只是简单处理,需要多个方式可以自己添加
if (object instanceofMap) {
Map map=(Map) object;
buildFlattenedMap(result, map,null);
}
reader.close();
}returnresult;
}/*** 这部分代码来至springboot源码部分对yaml的解析
* YamlProcessor.java buildFlattenedMap方法
*@paramresult
*@paramsource
*@parampath*/
private static void buildFlattenedMap(Map result, Mapsource, @Nullable String path) {//循环读取原数据
source.forEach((key, value) ->{//如果存在路径进行拼接
if(StringUtils.hasText(path)) {if (key.startsWith("[")) {
key= path +key;
}else{
key= path + '.' +key;
}
}//数据类型匹配
if (value instanceofString) {
result.put(key, value);
}else if (value instanceofMap) {//如果是map,就继续读取
Map map =(Map)value;
buildFlattenedMap(result, map, key);
}else if (value instanceofCollection) {
Collection collection =(Collection)value;if(collection.isEmpty()) {
result.put(key,"");
}else{int count = 0;
Iterator var7=collection.iterator();while(var7.hasNext()) {
Object object=var7.next();
buildFlattenedMap(result, Collections.singletonMap("[" + count++ + "]", object), key);
}
}
}else{
result.put(key, value!= null ? value : "");
}
});
}
}