我想更新(不覆盖)我现有的Yaml文件: YAML文件如下:
firstName: "John"
#text here
lastName: "Doe"
age: 20
#This is important
city: "XYZ"
我有Java类:
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String path = "E:/customer.yml";
Customer customer = objectMapper.readValue(new File(path), Customer.class);
customer.setAge(50);
objectMapper.writeValue(new FileWriter(path), customer);
和POJO模型:
private String firstName;
private String lastName;
private int age;
//getters setters
如何在不覆盖yaml文件的情况下更新它?实际上,在运行这些类之后,会修改值 Age ,但会删除其他属性,例如 city 。我知道,我可以更新POJO模型并添加城市,但是就我而言,我不确定文件中包含什么。 我可以将文件转换为String,并替换所需的数据,但是看起来并不专业。
答案 0 :(得分:0)
因为您不知道自己的POJO结构,也不想丢失任何数据。我建议您将文件读取到map。在POJO中创建地图,然后尝试使用注释@JsonAnyGetter
,@JsonAnySetter
。它们应该仍然可以工作,因为相同的库也可以用于JSON。
我认为“更新”是不可能的。之后,您可以读取并覆盖现有文件。这意味着您将失去评论。除非您要实施自己的解决方案-否则请阅读整个文件,找到char #
并保存这些行。