1.导入包
<!-- yaml文件处理包-->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.30</version>
</dependency>
2.调用工具类,可根据键值对获取map集合中的值;
package com.eshore.graph.utils;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.*;
public class YamlUtil {
/**
* yaml格式文件转map集合
* @param path 输入路径
* @return
*/
public static Map<String, Object> yamlToMap(String path){
FileInputStream fis = null;
Map<String, Object> map = null;
try {
//输入流
fis = new FileInputStream(new File(path));
//调用load方法 转到map集合中
map = new Yaml().load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return map;
}
public static Map<String, Object> yamlToMap(MultipartFile file){
Map<String, Object> map = null;
try {
//将MultipartFile中输入流直接放入load()方法中,调用load方法 转到map集合中
map = new Yaml().load(file.getInputStream());
} catch (IOException e){
e.printStackTrace();
}
return map;
}
/**
* 转为yaml文件
* @param map 需要转换map数据
* @param path 输出路径
* @param flag 是否追加写文件
*/
public static void mapToYaml(Map<String, Object> map, String path, boolean flag){
//将数据写入yaml文件
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml wyaml = new Yaml(dumperOptions);
//输出文件路径
File dumpfile = new File(path);
FileWriter fw = null;
try{
//输出流
fw = new FileWriter(dumpfile, flag);
//调佣dump方法 转到yaml文件中
wyaml.dump(map, fw);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3.完成解析,结束;