通过key值修改yml文件内容

直接修改yml,没有注释

1.引入pom

		<dependency>
			<groupId>org.yamlgroupId>
			<artifactId>snakeyamlartifactId>
			<version>2.0version>
		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){
         //        获取的是 java运行时候的classes里的文件地址
         //        String resourcePath = YamlUtils.class.getClassLoader().getResource(ymlUpdateName).getPath();
         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\\测试测试下");

修改yml文件包含注释

1.引入pom

        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-coreartifactId>
            <version>5.8.20version>
        dependency>

2. java 代码

    public static void YML_FILE_UPDATE_INCLUDE_REMARKS(String ymlUpdateName, String pathKey, String updateValue){
        String filePath = GET_YML_PATH(ymlUpdateName);
        List<String> list= FileUtil.readUtf8Lines(new File(filePath));
        String[] keys =pathKey.split("\\.");
        int i=0;
        int keyLength=keys.length;
        for (int j = 0; j < list.size(); j++) {
            String str =list.get(j);
            if(i!=keyLength&&str.contains(keys[i])){
                i++;
                if(i==keyLength){
                    String preFix=str.substring(0,str.indexOf(": ")+2);
                    list.set(j,preFix+updateValue);
                }
            }
        }
        FileUtil.writeUtf8Lines(list,new File(filePath));
    }

3.调用方式

YML_FILE_UPDATE_INCLUDE_REMARKS("application.yml","aaa.bbbb.ccc","D:\\1111\\dddd\\测试测试下");

你可能感兴趣的:(java,服务器,数据库)