In recent projects, you need to use Java to modify the configuration file of springboot, and you need to add or modify the value of a certain attribute. Snakeyaml was used to edit 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.
<dependency> <groupId></groupId> <artifactId>snakeyaml</artifactId> <version>1.17</version> </dependency>
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 and form a multi-level map structure containing the properties in the map to facilitate storage
* @param map map that needs to be initialized
* @author hongweidong
*/
public static Map<String, Object> initMap(Map<String, Object> map){
Map<String, Object> result = new LinkedHashMap<String, Object>();
(map);
for (String s : ()) {
if((s) == null){
(s,"");
}
if (s.split("\\.").length > 1) {
String key[] = ("\\.");
Map<String, Object> tarMap = new LinkedHashMap<String, Object>();
for (int i = 0; i < ; i++) {
if (i == - 1) {
//Last one
(key[i], (s));
} else {
if ((key[i]) != null) {
tarMap = (Map<String, Object>) (key[i]);
} else {
tarMap = (Map<String, Object>) (key[i]);
}
}
}
(s);
}
}
return result;
}
/**
* Test method
*/
public static void main(String args[]){
Map<String, Object> map = getYmlMap("F:/");
//Change the username value under primary under spring datasource under primary
("","root");
map = initMap(map);
try {
addIntoYaml("F:/",map);
} catch (IOException e) {
();
}
("");
}
public static void addIntoYaml(String dest, Map<String, Object> map) throws IOException {
map = (map);
Yaml yaml = new Yaml(OPTIONS);
//Load the current yml file
LinkedHashMap<String, Object> dataMap = (LinkedHashMap<String, Object>)(new FileReader(dest));
//If the content of yml is empty, a null pointer will be triggeredabnormal, Make a judgment here
if (null == dataMap) {
dataMap = new LinkedHashMap<String, Object>();
}
(map);
//Rewrite data back to file
(dataMap, new FileWriter(dest));
}
public static LinkedHashMap<String, Object> getYmlMap(String path){
File source = new File(path);
Yaml yaml = new Yaml(OPTIONS);
//Load the file
LinkedHashMap<String, Object> dataMap = null;
try {
dataMap = (LinkedHashMap<String, Object>)(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;
}
}