import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import scala.collection.immutable.Map;
import scala.util.Either;
import scala.util.parsing.combinator.Parsers;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.representer.Representer;
public class ScalaYamlExample {
private static final String YAML_FILE_PATH = "example.yaml";
public static void main(String[] args) {
String yamlContent = "";
try {
yamlContent = new String(Files.readAllBytes(Paths.get(YAML_FILE_PATH)));
} catch (IOException e) {
e.printStackTrace();
}
Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), new DumperOptions(),
new YamlClassLoader());
Either<String, Object> yamlResult = Parsers.parse(yamlContent, yaml);
if (yamlResult.isRight()) {
Object parsedYaml = yamlResult.right().get();
} else {
String errorMessage = yamlResult.left().get();
}
Map<String, Object> yamlData = Map.<String, Object>empty().updated("key1", "value1")
.updated("key2", 123).updated("key3", true);
String generatedYaml = yaml.dump(yamlData);
try {
Files.write(Paths.get("generated.yml"), generatedYaml.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}