Modify a YAML file with Java

In this tutorial, we explain how to load, modify and finally save some YAML data. We use the SnakeYAML library to achieve this.

YAML is a data-serialization language, that allows engineers to share data as readable text files easily. YAML is a JSON superset and has a very light human-friendly syntax. The YAML data format became very popular with cloud technologies like Docker, Kubernetes, Cloud Formation or Ansible.

1) Add SnakeYAML dependency to your pom.xml

In this tutorial we will use the excellent SnakeYAML library. So let’s add it to the pom.xml:


2) Load the YAML file as a Map<String,Object>

Any YAML file can be represented as a Map<String,Object> in memory. Simply do:

import org.yaml.snakeyaml.*;

String yamlPath = "path/to/yaml/file";
Map<String, Object> yaml = new Yaml().load(new FileReader(yamlPath));

, where you replaceyamlPath with the path to the YAML file you want to modify.

3) Modify the Map

You can now modify the Java Map that represents the YAML data:

yaml.put("foo", "bar");

List<String> li = new ArrayList<>();
yaml.put("li", li);

4) Save the modified YAML Map into a file

The last thing we want is to save the Map yaml variable into a .yml file:

String yamlModifiedPath = "path/to/modified/yaml/file";
DumperOptions options = new DumperOptions();     

String output = new Yaml(options).dump(yaml);
try (FileWriter fw = new FileWriter(yamlModifiedPath)) {

In the code above, replace yamlModifiedPath with the path of the file where you want to save the modified YAML.

5) Demo

Let’s run the above code with the following initial YAML file that we want to modify:

version: '3.1'
    image: springio/gs-spring-boot-docker:3.0

Then the modified YAML file is:

version: '3.1'
    image: springio/gs-spring-boot-docker:3.0
foo: bar
- a
- b

6) Modify nested YAML data

Of course you may do more complex modifications, by modifying nested fields for instance. If you want to modify the field spring in the above YAML, you can access it by doing:

Map<String, Object> services = (Map<String, Object>) yaml.get("services");
Map<String, Object> spring = (Map<String, Object>) services.get("spring");

That’s it for this tutorial ! If you have any question, please leave a reply below.

Leave a Reply

Your email address will not be published. Required fields are marked *