作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个使用 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/
我是一名优秀的程序员,十分优秀!