The below post explains how to write YAML data to file using YAMLGenerator. YAMLGenerator writes the data to a file in streaming way, helping the developer using the api to avoid
creating an object representation of the entire data.
We can get an instance of YAMLGenerator with the help of an instance of YAMLFactory as shown below.
YAMLFactory yamlFactory = new YAMLFactory();
YAMLGenerator yamlGenerator = yamlFactory.createGenerator(fw);
First we create an instance of YAMLFactory, then using the factory instance we create an instance of YAMLGenerator.
While creating a YAMLGenerator instance, we pass the FileWriter object (representing the file to which the data has to be written).
Below is the complete Main code
Main Code
package package1;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
public class YAMLDemo2 {
public static void main(String[] args) throws IOException {
File file = new File("Output1.yml");
YAMLFactory yamlFactory = new YAMLFactory();
try(FileWriter fw = new FileWriter(file);) {
YAMLGenerator yamlGenerator = yamlFactory.createGenerator(fw);
yamlGenerator.writeStartObject();
yamlGenerator.writeObjectField("firstName", "Duke");
yamlGenerator.writeObjectField("lastName", "Java");
yamlGenerator.writeObjectField("age", 18);
yamlGenerator.writeObjectField("streetAddress", "100 Internet Dr");
yamlGenerator.writeObjectField("city", "JavaTown");
yamlGenerator.writeObjectField("state", "JA");
yamlGenerator.writeObjectField("postalCode", "12345");
yamlGenerator.writeFieldName("phoneNumbers");
yamlGenerator.writeStartArray();
yamlGenerator.writeStartObject();
yamlGenerator.writeObjectField("Mobile", "111-111-1111");
yamlGenerator.writeEndObject();
yamlGenerator.writeStartObject();
yamlGenerator.writeObjectField("Home", "222-222-2222");
yamlGenerator.writeEndObject();
yamlGenerator.writeEndArray();
yamlGenerator.writeEndObject();
yamlGenerator.flush();
yamlGenerator.close();
}
}
}
We use the below methods
1) writeStartObject indicates the start of new object declaration
2) writeEndObject indicates the end of the object declaration
3) writeObjectField used to write a property of an object and set the property value.
4) writeFieldName used to write a property name but not its value
5) writeStartArray indicates the start of the array declaration
6) writeEndArray indicates the end of the array declaration
Below is the output
Output
firstName: “Duke”
lastName: “Java”
age: 18
streetAddress: “100 Internet Dr”
city: “JavaTown”
state: “JA”
postalCode: “12345”
phoneNumbers:
– Mobile: “111-111-1111”
– Home: “222-222-2222”