当前位置:   article > 正文

Java使用snakeyaml修改yaml方法_snakeyaml 更新yml

snakeyaml 更新yml

 一、依赖包

        pom引入snakeyaml依赖

  1. <dependency>
  2. <groupId>org.yaml</groupId>
  3. <artifactId>snakeyaml</artifactId>
  4. <version>2.0</version>
  5. </dependency>

二、代码实现yaml配置项修改

        上代码

  1. public class UpdateYmlConfigUtil {
  2. public static void updateYmlConfig(String config, Object value) {
  3. String src;
  4. String path = System.getProperty("user.dir");
  5. // 根据环境确定配置文件路径
  6. String system = System.getProperty("os.name");
  7. if(system.toLowerCase().startsWith("win")){
  8. src = path + "/src/main/resources/application.yml";
  9. } else {
  10. src = path + "/config/application.yml";
  11. }
  12. File file = new File(src);
  13. Yaml yaml = new Yaml();
  14. // 记录 yaml 文件的注释信息
  15. UpdateYmlConfigUtil.CommentHolder holder = UpdateYmlConfigUtil.buildCommentHolder(file);
  16. FileWriter fileWriter = null;
  17. //层级map变量
  18. Map<String, Object> springMap, dataSourceMap, resultMap;
  19. try {
  20. //读取yaml文件,默认返回根目录结构
  21. resultMap = yaml.load(new FileInputStream(file));
  22. String[] split = config.split("\\.");
  23. //get出第一个节点项
  24. dataSourceMap = (Map<String, Object>) resultMap.get(split[0]);
  25. for (int i = 1; i < split.length -1; i++) {
  26. //get出倒数第二个节点项
  27. dataSourceMap = (Map<String, Object>) dataSourceMap.get(split[i]);
  28. }
  29. //修改最后节点项配置的数据
  30. dataSourceMap.put(split[split.length -1], value);
  31. //字符输出
  32. fileWriter = new FileWriter(new File(src));
  33. //用yaml方法把map结构格式化为yaml文件结构
  34. fileWriter.write(yaml.dumpAsMap(resultMap));
  35. //刷新
  36. fileWriter.flush();
  37. //关闭流
  38. fileWriter.close();
  39. } catch (Exception e) {
  40. throw new RuntimeException("yml file config update fail:", e);
  41. }
  42. // 填充注释信息
  43. holder.fillComments(file);
  44. }
  45. private static final String END = "END###";
  46. private static final Pattern COMMENT_LINE = Pattern.compile("^\\s*#.*$");
  47. private static final Pattern BLANK_LINE = Pattern.compile("^\\s*$");
  48. /**
  49. * 带注释的有效行, 使用非贪婪模式匹配有效内容
  50. */
  51. private static final Pattern LINE_WITH_COMMENT = Pattern.compile("^(.*?)\\s+#.*$");
  52. @Data
  53. @AllArgsConstructor
  54. private static class Comment {
  55. private String lineNoComment;
  56. private String lineWithComment;
  57. // 存在相同行时的索引 (不同key下相同的行, 如 a:\n name: 1 和 b:\n name: 1 )
  58. private Integer indexInDuplicates;
  59. private boolean isEndLine() {
  60. return END.equals(lineNoComment);
  61. }
  62. }
  63. @SneakyThrows
  64. private static UpdateYmlConfigUtil.CommentHolder buildCommentHolder(File file) {
  65. List<UpdateYmlConfigUtil.Comment> comments = new ArrayList<>();
  66. Map<String, Integer> duplicatesLineIndex = new HashMap<>();
  67. UpdateYmlConfigUtil.CommentHolder holder = new UpdateYmlConfigUtil.CommentHolder(comments);
  68. List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8.toString());
  69. // 末尾加个标志, 防止最后的注释丢失
  70. lines.add(END);
  71. StringBuilder lastLinesWithComment = new StringBuilder();
  72. for (String line : lines) {
  73. if (StringUtils.isBlank(line) || BLANK_LINE.matcher(line).find()) {
  74. lastLinesWithComment.append(line).append('\n');
  75. continue;
  76. }
  77. // 注释行/空行 都拼接起来
  78. if (COMMENT_LINE.matcher(line).find()) {
  79. lastLinesWithComment.append(line).append('\n');
  80. continue;
  81. }
  82. String lineNoComment = line;
  83. boolean lineWithComment = false;
  84. // 如果是带注释的行, 也拼接起来, 但是记录非注释的部分
  85. Matcher matcher = LINE_WITH_COMMENT.matcher(line);
  86. if (matcher.find()) {
  87. lineNoComment = matcher.group(1);
  88. lineWithComment = true;
  89. }
  90. // 去除后面的空格
  91. lineNoComment = lineNoComment.replace("\\s*$", "");
  92. // 记录下相同行的索引
  93. Integer idx = duplicatesLineIndex.merge(lineNoComment, 1, Integer::sum);
  94. // 存在注释内容, 记录
  95. if (lastLinesWithComment.length() > 0 || lineWithComment) {
  96. lastLinesWithComment.append(line);
  97. comments.add(new UpdateYmlConfigUtil.Comment(lineNoComment, lastLinesWithComment.toString(), idx));
  98. // 清空注释内容
  99. lastLinesWithComment = new StringBuilder();
  100. }
  101. }
  102. return holder;
  103. }
  104. @AllArgsConstructor
  105. public static class CommentHolder {
  106. private List<UpdateYmlConfigUtil.Comment> comments;
  107. /**
  108. * 通过正则表达式移除匹配的行 (防止被移除的行携带注释信息, 导致填充注释时无法正常匹配)
  109. */
  110. public void removeLine(String regex) {
  111. comments.removeIf(comment -> comment.getLineNoComment().matches(regex));
  112. }
  113. @SneakyThrows
  114. private void fillComments(File file) {
  115. if (comments == null || comments.isEmpty()) {
  116. return;
  117. }
  118. if (file == null || !file.exists()) {
  119. throw new IllegalArgumentException("file is not exist");
  120. }
  121. List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8.toString());
  122. Map<String, Integer> duplicatesLineIndex = new HashMap<>();
  123. int comIdx = 0;
  124. StringBuilder res = new StringBuilder();
  125. for (String line : lines) {
  126. Integer idx = duplicatesLineIndex.merge(line, 1, Integer::sum);
  127. UpdateYmlConfigUtil.Comment comment = getOrDefault(comments, comIdx);
  128. if (comment != null &&
  129. Objects.equals(line, comment.lineNoComment)
  130. && Objects.equals(comment.indexInDuplicates, idx)) {
  131. res.append(comment.lineWithComment).append('\n');
  132. comIdx++;
  133. } else {
  134. res.append(line).append('\n');
  135. }
  136. }
  137. UpdateYmlConfigUtil.Comment last = comments.get(comments.size() - 1);
  138. if (last.isEndLine()) {
  139. res.append(last.lineWithComment, 0, last.lineWithComment.indexOf(END));
  140. }
  141. FileUtils.write(file, res.toString(), StandardCharsets.UTF_8.toString());
  142. }
  143. }
  144. private static <T> T getOrDefault(List<T> vals, int index) {
  145. if (vals == null || vals.isEmpty()) {
  146. return null;
  147. }
  148. if (index >= vals.size()) {
  149. return null;
  150. }
  151. return vals.get(index);
  152. }
  153. }

三、效果

        测试:

  1. public static void main(String[] args) {
  2. updateYmlConfig("a.b.c.d", "cd");
  3. }

        修改前:

                

        修改后:

                

四、参考资料

Java snakeyaml 修改yaml文件保留注释工具类封装_java 代码修改yml-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/449166
推荐阅读
相关标签
  

闽ICP备14008679号