<groupId>org.yaml
<artifactId>snakeyaml
<version>1.30</version> <!-- 使用最新版本 -->
</dependency>
public static void updateYamlContent(String absPath, String keyPath, Object newValue)throws IOException {
try {
// 从YAML文件读取内容
Map data =readYamlFile(absPath);
// 修改特定的键值
modifyYamlData(data, keyPath, newValue);
// 将修改后的数据写回文件
writeYamlFile(absPath, data);
}catch (IOException e) {
e.printStackTrace();
}
}
private static MapreadYamlFile(String filePath)throws IOException {
try (FileInputStream fis =new FileInputStream(filePath)) {
Yaml yaml =new Yaml(new Constructor(LinkedHashMap.class));
return yaml.load(fis);
}
}
private static void modifyYamlData(Map data, String keyPath, Object newValue) {
String[] keys = keyPath.split("_");
Map currentMap = data;
for (int i =0; i < keys.length -1; i++) {
currentMap = (Map) currentMap.get(keys[i]);
if (currentMap ==null) {
throw new IllegalArgumentException("Key path does not exist in the YAML data.");
}
}
currentMap.put(keys[keys.length -1], newValue);
}
private static void writeYamlFile(String filePath, Map data)throws IOException {
Writer output =new java.io.FileWriter(filePath);
Yaml yaml =new Yaml();
yaml.dump(data, output);
}
//mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl