Reputation: 1
I have a Yaml file which is in the below format:
connector:
Key1: Test
Key2: 22
Key3: Strringname
Key4: TestingFucntion
When I am trying to read the file and write it into another file the format is different. !!package name connector: {key1: Test, key2: 22 , key3: Strringname, key4: TestingFucntion}
Below is the code which i have used to read the file and write it :
Map<String, Object> data = new HashMap<String, Object>();
data.put(key1, value1);
DumperOptions options = new DumperOptions();
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.AUTO);
options.setPrettyFlow(true);
Yaml yaml = new Yaml();
InputStream in = new FileInputStream(new File(FIle name));
Prop cc = yaml.loadAs(in,Prop.class);
cc.getconnector().setkey3(Strringname);
Writer fwriter = new OutputStreamWriter(new FileOutputStream(File name), "UTF-8");
yaml.dump(cc, fwriter);
Any suggestions for writing the file in the same format as it is.
Upvotes: 0
Views: 705
Reputation: 39768
Use DumperOptions.FlowStyle.BLOCK
instead if you want to have the mapping in block style. You also need to tell the Yaml
constructor about your options
– right now, they don't do anything.
To remove the root tag and give the options to Yaml
, add
final Representer representer = new Representer();
representer.addClassTag(Prop.class, Tag.MAP);
Yaml yaml = new Yaml(representer, options);
This sets the tag of the class Prop
to !!map
, the default YAML tag for mappings. This will be omitted unless you're outputting it in canonical style.
That being said, the important thing is: In general, you cannot ensure that the format stays the same. SnakeYAML does not support that and doing so would technically be a breach of the specification. The keys will always written out in the order you defined in the Prop
class, not in the order in which they occurred in the original file. Deserialization drops information like whitespace, comments and other formatting details.
If you have any Map
in your data, the order of the keys will be arbitrary (as in: you cannot define or change it). If the original document contained ...
or ---
, that information will be lost. If the original document contained scalars with ''
or ""
, that information is lost.
You can only define consistent output behavior (i.e. define your options and always use them), but if the input uses a different style, that style will always be lost.
Upvotes: 0