You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jackson实现跨运行向JSON文件追加账户数据(避免覆盖)

解决Jackson保存账户信息到JSON文件不覆盖原有数据的问题

你的问题出在每次运行程序时都新建了一个空的ArrayNode,然后只把新输入的账户对象加进去,最后覆盖整个文件,自然会丢失之前的数据。要实现追加效果,需要先读取文件中已有的数组(如果存在),再把新对象加进去,最后写回文件。

下面是修改后的完整代码:

public static void accountSetup() throws IOException {
    // 初始化文件和Jackson核心对象
    File accountsFile = new File("accounts.json");
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    ArrayNode accountsArray;
    Scanner scan = new Scanner(System.in);

    // 读取现有数据或创建新数组
    if (accountsFile.exists() && accountsFile.length() > 0) {
        // 文件存在且非空,读取现有数组
        accountsArray = (ArrayNode) mapper.readTree(accountsFile);
    } else {
        // 文件不存在或为空,创建新数组
        accountsArray = mapper.createArrayNode();
    }

    // 获取用户输入(修复nextInt后的换行问题)
    System.out.println("What is the account holder's name?");
    String name = scan.nextLine();
    
    System.out.println("Please enter a 7-digit passcode");
    int passcode = scan.nextInt();
    // 吃掉nextInt留下的换行符,避免后续输入异常
    scan.nextLine();

    // 创建新账户对象并添加到数组
    ObjectNode newAccount = mapper.createObjectNode();
    newAccount.put("name", name);
    newAccount.put("passcode", passcode);
    accountsArray.add(newAccount);

    // 写回文件
    mapper.writeValue(accountsFile, accountsArray);
}

关键修改点说明:

  • 读取现有数据:通过accountsFile.exists() && accountsFile.length() > 0判断文件是否有有效内容,用mapper.readTree()读取已有的JSON数组,避免每次都新建空数组。
  • 修复Scanner输入异常:scan.nextInt()只会读取数字,不会处理输入后的换行符,后续的scan.nextLine()会读取空字符串,所以添加scan.nextLine()吃掉换行符。
  • 复用数组对象:不管是读取的旧数组还是新建的数组,都把新账户对象追加进去,再统一写回文件,实现数据累积效果。

验证效果

第一次运行输入Sam和1234567,第二次运行输入Max和7654321,accounts.json会生成你期望的结果:

[
  {
    "name" : "Sam",
    "passcode" : 1234567
  },
  {
    "name" : "Max",
    "passcode" : 7654321
  }
]

内容的提问来源于stack exchange,提问作者SourMnMs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:42:39