In recent projects, I need to use Java to modify the configuration file of springboot, and I need to add or modify the value of a certain attribute. I used snakeyaml to find that I edited the multi-level structure.yamlWhen it comes to files, the operation is relatively complicated, so it has been simplified, without having to do special processing every time, and uses a processing method similar to properties files.
MAVENon required dependencies.
snakeyaml
1.17
The code is as follows:
import ;
import ;
import .*;
import ;
import ;
import ;
/**
* @author hongweidong
* @desc Tool class for operating yaml files
* @date 2019-01-29 20:03
*/
public class YmlUtils {
private final static DumperOptions OPTIONS = new DumperOptions();
static {
//Set the default reading method to block reading
();
}
/**
* Initialize the map, form a multi-level map structure containing the properties in the map, which is convenient for saving
* @param map map that needs to be initialized
* @author hongweidong
*/
public static MapinitMap(Mapmap){
Mapresult = new LinkedHashMap();
(map);
for (String s : ()) {
if((s) == null){
(s,"");
}
if (s.split("\\.").length > 1) {
String key[] = ("\\.");
MaptarMap = new LinkedHashMap();
for (int i = 0; i < ; i++) {
if (i == - 1) {
//The last one
(key[i], (s));
} else {
if ((key[i]) != null) {
tarMap = (Map) (key[i]);
} else {
tarMap = (Map) (key[i]);
}
}
}
(s);
}
}
return result;
}
/**
* Test method
*/
public static void main(String args[]){
Mapmap = getYmlMap("F:/");
//Change the username value under primary under spring datasource under primary under spring root
("","root");
map = initMap(map);
try {
addIntoYaml("F:/",map);
} catch (IOException e) {
();
}
("");
}
public static void addIntoYaml(String dest, Mapmap) throws IOException {
map = (map);
Yaml yaml = new Yaml(OPTIONS);
//Load the current yml file
LinkedHashMapdataMap = (LinkedHashMap)(new FileReader(dest));
//If the content of yml is empty, a null pointer will be raisedabnormal, Make a judgment here
if (null == dataMap) {
dataMap = new LinkedHashMap();
}
(map);
//Rewrite data back to file
yaml.dump(dataMap, new FileWriter(dest));
}
public static LinkedHashMapgetYmlMap(String path){
File source = new File(path);
Yaml yaml = new Yaml(OPTIONS);
//Load the file
LinkedHashMapdataMap = null;
try {
dataMap = (LinkedHashMap)(new FileReader(source));
} catch (FileNotFoundException e) {
();
}
//Get the value under the current key (if there are multiple nodes, the value may be map, judge by yourself)
return dataMap;
}
}