最近做的项目里需要用java修改springboot的配置文件,需要新增或修改某一个属性的值,使用了snakeyaml发现在编辑多级结构的yaml文件时,操作较为复杂,所以做了些简化,不用每次都做特殊处理,使用类似于properties文件的处理方式。
MAVEN上所需依赖。
org.yaml
snakeyaml
1.17
代码如下:
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class YmlUtils {
private final static DumperOptions OPTIONS = new DumperOptions();
static {
//将默认读取的方式设置为块状读取
OPTIONS.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
}
public static MapinitMap(Mapmap){
Mapresult = new LinkedHashMap();
result.putAll(map);
for (String s : map.keySet()) {
if(map.get(s) == null){
map.put(s,"");
}
if (s.split("\\.").length > 1) {
String key[] = s.split("\\.");
MaptarMap = new LinkedHashMap();
for (int i = 0; i < key.length; i++) {
if (i == key.length - 1) {
//最后一位
tarMap.put(key[i], map.get(s));
} else {
if (result.get(key[i]) != null) {
tarMap = (Map) result.get(key[i]);
} else {
tarMap = (Map) tarMap.get(key[i]);
}
}
}
result.remove(s);
}
}
return result;
}
public static void main(String args[]){
Mapmap = getYmlMap("F:/application.yml");
//把spring下datasoource下primary下username的值改变root
map.put("spring.datasource.primary.username","root");
map = initMap(map);
try {
addIntoYaml("F:/application.yml",map);
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("");
}
public static void addIntoYaml(String dest, Mapmap) throws IOException {
map = YmlUtils.initMap(map);
Yaml yaml = new Yaml(OPTIONS);
//载入当前yml文件
LinkedHashMapdataMap = (LinkedHashMap)yaml.load(new FileReader(dest));
//如果yml内容为空,则会引发空指针异常,此处进行判断
if (null == dataMap) {
dataMap = new LinkedHashMap();
}
dataMap.putAll(map);
//将数据重新写回文件
yaml.dump(dataMap, new FileWriter(dest));
}
public static LinkedHashMapgetYmlMap(String path){
File source = new File(path);
Yaml yaml = new Yaml(OPTIONS);
//载入文件
LinkedHashMapdataMap = null;
try {
dataMap = (LinkedHashMap)yaml.load(new FileReader(source));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//获取当前key下的值(如果存在多个节点,则value可能为map,自行判断)
return dataMap;
}
}