Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中写入json文件而不重写_Java_Json_Spring - Fatal编程技术网

如何在Java中写入json文件而不重写

如何在Java中写入json文件而不重写,java,json,spring,Java,Json,Spring,我有一个方法,可以使用ObjectMapper将数据存储到json文件中。这很好。但当我尝试添加新数据时,它会清除以前的数据。在没有清除文件的情况下,它们仍然可以写入 public String addnews(@ModelAttribute("SpringWeb")Story story, ModelMap model,HttpServletRequest request) { ObjectMapper mapper = new ObjectMapper();

我有一个方法,可以使用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);

commons io提供了这样一种功能:这是做您想做的事情的最简单的方法,您可以将数据存储为Json对象,如下[{“storyTitle”:“test”,“storyBody”:“sdzfdsaf”,“storyAuthor”:“asdfasdf”}{“storyTitle”:“TestsSdFadsf”,“storyBody”:“Sdzfdasdfasf”,“storyAuthor”:“asdfasdf”}]您的ans在没有[]的情况下创建数据您需要手动添加此内容,因为它不是标准的JSON格式,那么我如何才能取回所有这些数据