简体   繁体   English

如何使用Spring Boot Rest Java EE项目正确管理对文件的写入?

[英]How to manage writing to file correctly using Spring Boot Rest Java EE project?

I am trying to update a JSON file on my server resources folder in response to a form submission to my api endpoint. 我正在尝试更新服务器资源文件夹中的JSON文件,以响应将表单提交到我的api端点。

项目目录结构

I want to update my QueryMap.json from the controller QueryMapController.java 我想从控制器QueryMapController.java更新我的QueryMap.json

这是QueryMap.json文件

     @CrossOrigin
   @RequestMapping("/newQuery")
    public String newQuery(@RequestParam("qid") String qid, @RequestParam("query") String query) throws Exception{

    String fileName="QueryMap.json";

     File file = new ClassPathResource(fileName).getFile();




      JSONParser parser = new JSONParser();
      FileReader fr = new FileReader(file);
     Object ob = parser.parse(fr);
     fr.close();


     JSONArray arr = (JSONArray)ob;

     JSONObject newob = new JSONObject();
     newob.put("Query_id",qid);
     newob.put("Query",query);

     arr.add(newob);


     FileWriter fw = new FileWriter(file.getAbsoluteFile(),false);
     BufferedWriter out = new BufferedWriter(fw);
     out.write(arr.toJSONString());
     out.flush();
     out.close();
     fw.close();

   return arr.toJSONString();

} }

The above code is the Controller Method I want to use to update my .json file. 上面的代码是我想用来更新.json文件的Controller方法。 Apparently Everything seems to work. 显然,一切似乎正常。 It works without errors and the program executes as if the file is updated but the actual file is not changed. 它可以正常工作,并且程序执行时就像文件已更新,但实际文件未更改一样。 As I restart the server the changes are gone. 当我重新启动服务器时,更改已消失。 It seems the file is cached somewhere internally during runtime. 似乎文件在运行时内部缓存在某个地方。 How should I handle this. 我该如何处理。

Pardon my Custom Data Connection and writing code like this which doesn't strictly follow MVC guidelines. 请原谅我的自定义数据连接并编写类似这样的代码,但这些代码并不严格遵循MVC准则。 It has reasons behind to code this way. 用这种方式进行编码有其背后的原因。

tl;dr Place files you want to modify outside of your classpath because they are overwritten with the ones in your <projectDir>/src/main/resources directory when you build/package your project. tl; dr将要修改的文件放在类路径之外,因为在构建/打包项目时,这些文件会被<projectDir>/src/main/resources目录中的文件覆盖。 If you want to see code for this check the end of the answer. 如果您想查看此代码,请查看答案的结尾。


The reason this happens is most likely because when you restart your server, your project is re-build. 发生这种情况的原因很可能是因为重新启动服务器时,将重新构建项目。 During this process every class is re-compiled and the compiled classes are placed in a separate directory, along with all the resources ( <projectDir>/target/classes/ when using maven). 在此过程中,将重新编译每个类,并将所有资源(使用maven时, <projectDir>/target/classes/ )连同所有资源一起放置在单独的目录中。 This replaces your changed version of the json file with the original one from your <projectDir>/src/main/resources directory. 这将用<projectDir>/src/main/resources目录中的原始文件替换更改后的json文件版本。

You can verify this by debugging your newQuery Method and following these steps: 您可以通过调试newQuery方法并按照以下步骤进行验证:

  1. Check the location of your json file with File.getAbsolutePath() . 使用File.getAbsolutePath()检查json文件的位置。 For me it is <projectDir>/target/classes/QueryMap.json . 对我来说,它是<projectDir>/target/classes/QueryMap.json
  2. Check the content of the file, it should be in its original state. 检查文件的内容,它应该处于原始状态。
  3. Let your code do the changes, then re-check the file content. 让您的代码进行更改,然后重新检查文件内容。 The changes should be there. 更改应该在那里。
  4. Stop the server and re-build your project (With maven mvn clean package ). 停止服务器并重新构建您的项目(使用maven mvn clean package )。
  5. The file content should be in its original state again, because the build process replaced <projectDir>/target/classes/QueryMap.json with <projectDir>/src/main/resources/QueryMap.json . 文件内容应再次处于其原始状态,因为构建过程将<projectDir>/target/classes/QueryMap.json替换为<projectDir>/src/main/resources/QueryMap.json

One solution to this would be to use the json file on your class path as a default and copy it to the current working directory where you can change it any way you want: 一种解决方案是将您的类路径上的json文件用作默认文件,并将其复制到当前工作目录中,您可以在其中以任何所需的方式对其进行更改:

File editableQueryMap = new File("./QueryMap.json");

    if (!editableQueryMap.exists()) {
      File defaultQueryMap = new ClassPathResource("QueryMap.json").getFile();

      try (OutputStream os = Files.newOutputStream(editableQueryMap.toPath())) {
        Files.copy(defaultQueryMap.toPath(), os);
      }
    }

    //do your changes with editableQueryMap here

For me, this puts the editable QueryMap.json file in the root of my project directory. 对我来说,这会将可编辑的QueryMap.json文件放在我的项目目录的根目录中。 If you use a jar file, it should place the file in the same directory as the jar (unless the working directory is changed). 如果使用jar文件,则应将文件放置在与jar相同的目录中(除非更改了工作目录)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM