How do I write to a YAML file using SnakeYaml?
Else one way to write data
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
YamlWriter writer = new YamlWriter(new FileWriter("test.yml"));
writer.write(map);
writer.close();
Output:
key1: value1
key2: value2
key3: value3
For me, in this case, I see a more readable output. From the first solution, we will see output like this:
{key1: value1, key2: value2, key3: value3}
If we will have a lot of data it will be hard to read
P.S. we need some dependency
<dependency>
<groupId>com.esotericsoftware.yamlbeans</groupId>
<artifactId>yamlbeans</artifactId>
<version>1.13</version>
</dependency>
If I've understood the question, it doesn't seem to have anything to do with YAML or SnakeYAML per se, but to do with how you write to a specific file in Java. Basically, what the second example you copied is showing is how to dump an object to an arbitrary java.io.Writer
object (though they use a StringWriter
as this will not write anything to disk). If you want to modify this example to write to a particular file, you can do so by making use of a FileWriter
, like so:
public void testDumpWriter() {
Map<String, Object> data = new HashMap<String, Object>();
data.put("name", "Silenthand Olleander");
data.put("race", "Human");
data.put("traits", new String[] { "ONE_HAND", "ONE_EYE" });
Yaml yaml = new Yaml();
FileWriter writer = new FileWriter("/path/to/file.yaml");
yaml.dump(data, writer);
}
Which will dump the map data
to a YAML file. Note that it is not normally necessary to create the file yourself before opening the FileWriter
as the FileWriter
will handle that for you.
To pretty print in expected yaml format (without the braces, like in accepted answer):
public static void saveYamlToFile(final Object object) throws IOException {
final DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
final Yaml yaml = new Yaml(options);
final FileWriter writer = new FileWriter("/path/to/file.yaml");
yaml.dump(object, writer);
}