
在 java 中将 json 转为 excel 后无法删除源 json 文件,通常是因为 `filereader` 未正确关闭,导致文件句柄被占用;使用 try-with-resources 自动管理资源可彻底避免该问题。
在您提供的代码中,核心问题在于这一行:
Object obj = parser.parse(new FileReader(".//Json_files//db-" + stockname + ".json"));此处直接将 FileReader 作为参数传入 parser.parse(),但未显式关闭流。FileReader 是基于操作系统文件句柄的资源,若未及时释放,Windows 系统会锁定该文件(表现为 FileSystemException: The process cannot access the file because it is being used by another process),导致后续 Files.deleteIfExists() 失败。
✅ 正确做法:使用 try-with-resources 语句确保 FileReader 在解析完成后自动关闭:
JSONParser parser = new JSONParser();
Object obj;
try (FileReader reader = new FileReader(".//Json_files//db-" + stockname + ".json")) {
obj = parser.parse(reader); // 解析完成后 reader 自动关闭
} catch (IOException | ParseException e) {
throw new RuntimeException("Failed to parse JSON file: " + stockname, e);
}⚠️ 其他需同步修复的关键点(否则仍可能引发资源泄漏或并发问题):
- 避免静态流对象:当前代码中 public static FileInputStream fi; 和 public static FileOutputStream fo; 被声明为 static,不仅违背面向对象设计原则,还极易引发多线程/多轮执行时的资源冲突。应改为局部变量;
-
Excel 写入后务必关闭 FileOutputStream:您已在 fo.close() 前调用 fo.flush(),这是正确的,但建议同样用 try-with-resources 封装:
try (FileOutputStream fo = new FileOutputStream(dir + "//DB_Search" + "-" + formatedate + ".xlsx")) { wb.write(fo); } -
JSON 文件写入也应安全关闭:当前使用 PrintWriter 写入 JSON,虽已调用 out.close(),但建议同样采用 try-with-resources 防御异常中断导致未关闭:
try (PrintWriter out = new PrintWriter(new FileWriter(".//Json_files//db-" + stockname + ".json", true), true)) { out.write(resp.asString()); }
? 总结与最佳实践:
- 所有实现 AutoCloseable 的资源(FileReader, FileWriter, PrintWriter, FileInputStream, FileOutputStream, Workbook 等)都应优先使用 try-with-resources;
- 避免 static 流字段——它们生命周期过长、状态共享,是资源泄漏和线程不安全的温床;
- 删除文件前可增加诊断逻辑(非必须,但便于调试):
Path jsonPath = Paths.get(".//Json_files//db-" + stockname + ".json"); if (!Files.exists(jsonPath)) { System.out.println("JSON file does not exist: " + jsonPath); } else if (!Files.isWritable(jsonPath)) { System.out.println("JSON file is not writable — may be locked or permission denied."); }
遵循以上改进后,JSON 文件将在解析完成即刻释放,Files.deleteIfExists() 将稳定执行成功,彻底解决“文件被占用”异常。










