gpt4 book ai didi

java - 如何在Java中写入json文件而不覆盖

转载 作者:行者123 更新时间:2023-12-02 04:03:53 25 4
gpt4 key购买 nike

我有一个使用 ObjectMapper 将数据存储到 json 文件的方法。它很好。但是当我尝试添加新数据时,它会清除以前的数据。无论如何,他们是否要在没有清除文件的情况下写入。

 public String addnews(@ModelAttribute("SpringWeb")Story story, 
ModelMap model,HttpServletRequest request) {
ObjectMapper mapper = new ObjectMapper();
try{
String phyPath = request.getSession().getServletContext().getRealPath("/");
String filepath = phyPath + "resources/" + "data.json";
File file = new File(filepath);
if (!file.exists()) {
System.out.println("pai nai");
file.createNewFile();
}
mapper.writeValue(file, story);
mapper.writerWithDefaultPrettyPrinter().writeValueAsString( story);
System.out.println("Done");
}
catch (IOException e) {
e.printStackTrace();
}

return "result";
}
Also how can i get back all those data

最佳答案

您可以使用java.nio.file.Files库,例如:

// Create JSON
final String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(story);

// Content is appended (due to StandardOpenOption.APPEND)
Files.write(new File(filepath).toPath(), Arrays.asList(json), StandardOpenOption.APPEND);

关于java - 如何在Java中写入json文件而不覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34580090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com