Java读取yaml数据

YAML

YAML 数据结构可以用类似大纲的缩排方式呈现,结构通过缩进来表示,连续的项目通过减号“-”来表示,map结构里面的key/value对用冒号“:”来分隔。

下面介绍两种 Java 读取 Yaml 内容的方式:

1.SnakeYaml

忽略注释的方式,读写会导致注释丢失

  • 在pom.xml加入snakeyaml依赖:
      <!-- read and write yaml file -->
      <dependency>
		    <groupId>org.yaml</groupId>
		    <artifactId>snakeyaml</artifactId>
		    <version>1.29</version>
      </dependency>
  • 具体java代码:
public class YamlUtils {
    private static final Logger logger = LoggerFactory.getLogger(YamlUtils.class);

    // yml2Map: Yaml to Map, 将yaml文件读为map
    public static Map<String, Object> yml2Map(String path) throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(path);
        Yaml yaml = new Yaml();
        Map<String, Object> ret = (Map<String, Object>) yaml.load(fileInputStream);
        return ret;
    }

    // map2Yml: Map to Yaml, 将map转换为yaml格式
    public static void map2Yml(Map<String, Object> map, String path) throws IOException {

        File file = new File(path);
        FileWriter fileWriter = new FileWriter(file);
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml yaml = new Yaml(options);
        yaml.dump(map, fileWriter);
    }
 }

2.eo-yaml:

  • 支持注释读写的yaml包;
  • 读取的时候,生成节点,在每一个节点上保存相应的注释;
  • 写入的时候,根据节点,重新添加相应的注释;
<dependency>
    <groupId>com.amihaiemil.web</groupId>
    <artifactId>eo-yaml</artifactId>
    <version>4.3.5</version>
</dependency>
YamlMapping team = Yaml.createYamlInput(
    new File(path)
).readYamlMapping();
String architect = team.string("architect");
YamlSequence devs = team.yamlSequence("developers");
YamlSequence devops = team.yamlSequence("devops");
Map<String, Integer> grades = new HashMap<>();
grades.put("Math", 9);
grades.put("CS", 10);
YamlMapping student = Yaml.createYamlDump(
    new Student ("John", "Doe", 20, grades)
).dumpMapping();
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java读取YAML文件内容包括注释可以通过以下步骤实现: 1. 引入YAML解析库,如jyaml或snakeyaml。 2. 使用YAML解析库读取YAML文件内容。 3. 将读取到的内容存储到一个Map对象中,其中包含键值对和注释。 以下是一个示例代码: ```java import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.reader.StreamReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.*; public class YamlReader { public static void main(String[] args) { Yaml yaml = new Yaml(); try { InputStream stream = new FileInputStream("test.yaml"); Map<String, Object> document = (Map<String, Object>) yaml.load(stream); Map<String, List<String>> comments = extractComments(stream); for (Map.Entry<String, Object> entry : document.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); List<String> commentList = comments.get(key); if (commentList != null) { for (String comment : commentList) { System.out.println(comment); } } System.out.println(key + ": " + value); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private static Map<String, List<String>> extractComments(InputStream stream) { Map<String, List<String>> comments = new HashMap<>(); try { StreamReader reader = new StreamReader(stream); while (reader.hasMore()) { Node node = reader.peekNode(); if (node != null && node.getStartMark().getColumn() == 0 && node.getEndMark().getColumn() == 0) { List<String> commentList = new ArrayList<>(); while (node != null && node.getStartMark().getColumn() == 0 && node.getEndMark().getColumn() == 0) { commentList.add(reader.getNextLine()); node = reader.peekNode(); } comments.put(node.getStartMark().getLine() + "", commentList); } else { reader.getNextLine(); } } } catch (Exception e) { e.printStackTrace(); } return comments; } } ``` 在这个示例中,我们使用了SnakeYAML库来读取YAML文件内容,并使用extractComments方法从文件中提取注释。在主方法中,我们遍历读取到的内容,根据每个键值对的键从注释Map中获取注释,并将注释和值一起输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值