Skip to content

YAML Printer

Mihai A edited this page Jan 25, 2024 · 5 revisions

YAML Printer

We offer a YamlPrinter which you can create and use like this:

final YamlMapping map = ...;
final YamlPrinter printer = Yaml.createYamlPrinter(/* any java.io.Writer */);
printer.print(map);

It works with any implementation of java.io.Writer. For instance, to print the YAML to a file, all you have to do is:

final YamlMapping map = ...;
final YamlPrinter printer = Yaml.createYamlPrinter(
    new FileWriter("/path/to/map.yml")
);
printer.print(map); //file map.yml will be created and written.

We also offer the overloaded method Yaml.createYamlPrinter(Writer writer, String lineSeparator), so you can customize the line endings (by default, System.lineSeparator() is used).

Print As String

All the toString() methods are already implemented using a YamlPrinter that works with a StringWriter. This means, the following code snippets are equivalent:

final YamlMapping map = ...;
System.out.println(map.toString());
final YamlMapping map = ...;
final StringWriter stgw = new StringWriter();
final YamlPrinter printer = Yaml.createYamlPrinter(stgw);
printer.print(map);
System.out.println(stgw.toString());

The Writer Is Flushed At The End

Pay attention, the provided java.io.Writer will be flushed and closed at the end of the printing, which means you can only call the print(...) method once. The second call may throw an IOException.

Yaml Visitor

We offer the interface YamlVisitor which you can use to implement your own printer if you're not happy with the defaults.