Java Can';t在使用JSONObject和ObjectMapper编辑后删除文件
我正在使用java编辑包含JSON的文件:Java Can';t在使用JSONObject和ObjectMapper编辑后删除文件,java,json,jackson,Java,Json,Jackson,我正在使用java编辑包含JSON的文件: public void editApi(String path, String nameOfOldApi, API updatedApi) throws IOException, ParseException { String apiPath = path + "\\" + updatedApi.getTeamName() + "\\"; Gson gson = new Gson(); ObjectMapper mapp
public void editApi(String path, String nameOfOldApi, API updatedApi)
throws IOException, ParseException
{
String apiPath = path + "\\" + updatedApi.getTeamName() + "\\";
Gson gson = new Gson();
ObjectMapper mapper = new ObjectMapper();
String updatedJsonString = gson.toJson(updatedApi);
JSONObject jsonToBeEditted = mapper.readValue(new File(apiPath + nameOfOldApi + ".json"), JSONObject.class);
JSONObject updatedJson = mapper.readValue(updatedJsonString, JSONObject.class);
for (Object key : jsonToBeEditted.keySet()) {
if (key.equals("tags") || key.equals("paths")) {
continue;
} else if (!jsonToBeEditted.get(key).equals(updatedJson.get(key))) {
System.out.println(jsonToBeEditted.get(key) + "--->" + updatedJson.get(key));
jsonToBeEditted.put(key, updatedJson.get(key));
}
}
mapper.writeValue(new File(apiPath + updatedApi.getInfo().getTitle() + ".json"), jsonToBeEditted);
if (!updatedApi.getInfo().getTitle().equals(nameOfOldApi)) {
Files.delete(new File(apiPath + nameOfOldApi + ".json").toPath());
}
}
当我运行这个程序(如果相关的话,它是一个spring应用程序)并调用它时,它第一次就可以正常工作。但是如果我再次尝试编辑同一个文件,我会得到一个FileSystemException,表示该文件正被另一个进程使用。例如,如果我有一个文件“test.json”,并将其编辑为“test edit.json”,它会正确地添加新文件并删除旧文件。但是,如果我随后将“test edit.json”编辑为“test edit reach.json”,则会抛出以下错误:
java.nio.file.FileSystemException:C:\stackoverflow.json:进程无法访问
由于另一个进程正在使用该文件,因此无法删除该文件。
我不知道发生在哪里。。。我觉得在
ObjectMapper.writeValue()调用中有些东西没有正确关闭,但我不确定。删除该文件之前,您必须关闭访问该文件的所有连接。例如,关闭mapper
stream我尝试过这样做,但似乎没有办法通过自己的方法关闭mapper。是否有其他方法关闭流?ObjectMapper
没有保持文件打开,而是其他方法。如果看不到更多的代码,就无法告诉您是什么在做。谢谢,肖恩。至少知道这不是什么是好的,哈哈。