我有一种使用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);

09-11 07:16
查看更多