Java读取yaml数据

文章介绍了在Java中使用SnakeYaml和eo-yaml库读取和写入YAML文件的方法。SnakeYaml不支持注释的读写,而eo-yaml则能保留和处理YAML文件中的注释。示例代码展示了如何将YAML文件转换为Map以及如何从Map生成YAML文件。
摘要由CSDN通过智能技术生成

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配置,你可以使用第三方库如snakeyaml、jackson-dataformat-yaml或beetl等。这里以snakeyaml为例来说明: **1. 添加依赖** 首先,你需要在你的Maven或Gradle项目中添加snakeyaml的依赖。如果你使用Maven,可以在pom.xml文件中添加: ```xml <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.36</version> </dependency> ``` 如果你使用Gradle,可以在build.gradle文件中添加: ```groovy implementation 'org.yaml:snakeyaml:1.36' ``` **2. 读取YAML配置** 然后,你可以使用`Yaml`类从YAML文件中加载数据。这里是一个基本的例子: ```java import org.yaml.snakeyaml.Yaml; public class ConfigReader { private Yaml yaml = new Yaml(); public Map<String, Object> loadConfig(String filePath) { try (InputStream inputStream = new FileInputStream(filePath)) { return yaml.load(inputStream); } catch (IOException e) { throw new RuntimeException("Failed to read YAML file", e); } } public String getConfigValue(String key, String defaultValue) { Map<String, Object> configMap = loadConfig("config.yaml"); return configMap.containsKey(key) ? configMap.get(key).toString() : defaultValue; } } ``` 在这个例子中,`loadConfig`方法会读取指定路径的YAML文件,并返回一个包含所有配置的Map。然后你可以通过键来获取具体的值。 **3. 相关问题--:** 1. 是否还有其他Java库可以用来解析YAML?如果有的话,它们之间有什么区别? 2. 在处理YAML文件时,如何处理嵌套的数据结构? 3. 如果YAML文件不存在或者格式错误,如何处理异常?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值