如何在Java中向JSON文件追加新对象而非覆盖原有内容
问题描述
我正在构建一个GSONFileWriter类,当前代码可以创建包含单个员工对象的JSON文件,但每次运行代码时,原有文件会被覆盖。我希望修改代码,实现向JSON文件中添加新对象而非覆盖的功能。
当前GSONFileWriter代码:
public class GSONFileWriter { private File jsonFile; private final String json; public GSONFileWriter(String json) { this.json = json; } public void generateJsonFileIfNotExists(String pathname) { try { jsonFile = new File(pathname); if (!jsonFile.exists()) { if (jsonFile.createNewFile()) { System.out.println("File successful created."); } else { System.out.println("Error: Building the file went wrong!"); System.exit(1); } } fillJsonFile(); } catch (Exception e) { System.err.println("Error: Building the file went wrong!"); } } private void fillJsonFile() { try (PrintWriter writer = new PrintWriter(jsonFile, StandardCharsets.UTF_8)) { writer.append(json); writer.println(); } catch (Exception e) { e.printStackTrace(); } } }
CLI调用代码:
Gson gson = new Gson(); String json = gson.toJson(target); GSONFileWriter gsonFileWriter = new GSONFileWriter(json); gsonFileWriter.generateJsonFileIfNotExists("EmployeeData.json");
当前生成的JSON文件内容:
{"salary":34000.0,"name":"Hans","age":30,"id":"d40507a7-a802-4494-9a0c-5a97a0a4d0bf"}
解决方案
原代码的核心问题有两个:
PrintWriter默认以覆盖模式打开文件,而非追加;- 直接追加单个JSON对象会导致文件内容不是合法的JSON格式(多个独立的JSON对象无法被标准解析器识别)。
推荐采用读取原有数据→合并新对象→重新写入的方式,既保证追加逻辑,又维护JSON格式的合法性:
修改后的GSONFileWriter类
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.*; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class GSONFileWriter { private final String json; private static final Gson gson = new Gson(); // 定义员工列表的类型令牌,用于GSON反序列化 private static final Type EMPLOYEE_LIST_TYPE = new TypeToken<List<Object>>() {}.getType(); public GSONFileWriter(String json) { this.json = json; } public void appendEmployeeToFile(String pathname) { File jsonFile = new File(pathname); List<Object> employees = new ArrayList<>(); try { // 读取已有员工数据(如果文件存在且非空) if (jsonFile.exists() && jsonFile.length() > 0) { try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile, StandardCharsets.UTF_8))) { employees = gson.fromJson(reader, EMPLOYEE_LIST_TYPE); // 防止读取失败导致列表为空 if (employees == null) { employees = new ArrayList<>(); } } } // 将新员工对象加入列表 Object newEmployee = gson.fromJson(json, Object.class); employees.add(newEmployee); // 将更新后的列表写入文件 try (FileWriter writer = new FileWriter(jsonFile, StandardCharsets.UTF_8)) { gson.toJson(employees, writer); } System.out.println("员工数据已成功追加"); } catch (Exception e) { System.err.println("写入失败: " + e.getMessage()); e.printStackTrace(); } } }
修改CLI调用代码
Gson gson = new Gson(); String json = gson.toJson(target); GSONFileWriter gsonFileWriter = new GSONFileWriter(json); // 调用新的追加方法 gsonFileWriter.appendEmployeeToFile("EmployeeData.json");
方案说明
- 该方法先读取文件中已有的员工列表,合并新对象后重新写入,保证文件始终是合法的JSON数组;
- 对于大文件场景,如果担心性能问题,可以改用「追加式维护JSON数组」的方式:文件创建时写入
[,每次追加时写入,\n{新对象},最后在程序退出时写入],但这种方式存在程序异常退出导致JSON格式损坏的风险,因此更推荐上述安全方案。
内容的提问来源于stack exchange,提问作者Onizuka92
相关产品推荐
相关产品推荐

