java读取yaml文件内容

直接上代码

  /**
     * 获取yaml文件内容
     *
     * @param yamlPath yaml文件路径
     * @return
     */
    public static Map getYamlMsg(String yamlPath) {
        Map<String, Map<String, Object>> properties = new HashMap<>();
        InputStream in = null;
        try {
            Yaml yaml = new Yaml();
            in = new FileInputStream(yamlPath);
            properties = yaml.loadAs(in, HashMap.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return properties;
    }
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
发出的红包

打赏作者

飞机飞上天空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值