Read YAML file in Java

(1) Import Jackson YAML. E.g. via Maven.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.8.8</version>
</dependency>

(2) Create your YAML file. E.g. my-config.yml

key_one: value1
key_two: value2

(3) Create a JAVA class to hold your config. E.g.

package calvin;

public class Config {
    private String key_one;
    private String key_two;

    public String getKey_one() { return key_one; }
    public void setKey_one(String key_one) { this.key_one = key_one; }

    public String getKey_two() { return key_two; }
    public void setKey_two(String key_two) { this.key_two = key_two; }
  }

(4) Load your config file.

public static void main(String[] args) {
  final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
  config = mapper.readValue(new File("my-config.yml"), Config.class);
}

(5) To debug your config data. You can print the following:

ReflectionToStringBuilder.toString(config, ToStringStyle.MULTI_LINE_STYLE)

Note that Apache common-lang is required.


AI Summary
Chrome On-device AI 2024-07-20 05:30:55

Share Article