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

标签 java json spring

我有一个使用 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/

相关文章:

javascript - 如何使用 JavaScript 数组通过 for 循环一次性检索 JSON 对象的值

javascript - jquery中json循环后的命令

php - 如何使用 Web 表单发送交易?

java - Spring 批处理在特定时间启 Action 业

java - 当使用 JtaTransactionManager 时,为什么使用 EntityManager 进行的 JPA 更改未在 Spring 服务中提交?

java - 无法使用 selenium 传递客户 ID 中的任何值

java - CheckBox 矩阵出现问题,循环不起作用

java - 与 gradle intellij 一起使用的环境变量 - spring boot

java - Glassfish 不处理 java

java - 如何打印带有用户占用的空格的字符串?