1.引入pom
<dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>2.0</version></dependency>
2. JAVA代码
public static void YML_FILE_UPDATE(String ymlOriginName, String ymlUpdateName, String pathKey, String updateValue){DumperOptions options = new DumperOptions();options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);Yaml yaml = new Yaml(options);Object ymlDataMap = yaml.load(YamlUtils.class.getClassLoader().getResourceAsStream(ymlOriginName));String[] keys = pathKey.split("\\.");Object updateObj=ymlDataMap;for (int i = 1; i <= keys.length; i++) {if(i==keys.length){((LinkedHashMap) updateObj).put(keys[i-1],updateValue);}else {updateObj = ((Map<String, Object>) updateObj).get(keys[i-1]);}}try {yaml.dump(ymlDataMap, new FileWriter(GET_YML_PATH(ymlUpdateName)) );} catch (IOException e) {e.printStackTrace();}}private static String GET_YML_PATH(String ymlUpdateName){String resourcePath = Thread.currentThread().getContextClassLoader().getResource(ymlUpdateName).getPath();return resourcePath.replace("/target/classes/","/src/main/resources/").replaceAll("/","\\\\");}
3.调用方式
YML_FILE_UPDATE("application.yml","aaa.bbbb.ccc","D:\\1111\\dddd\\测试测试下");