首页 > 解决方案 > 修改一个值并将 JSON 写入文件

问题描述

我正在尝试修改 JSON 并将修改后的 JSON 写入文件。但是写入 JSON 的输出文件是空的。

{
    "id": 4051,
    "name": "menad",
    "livelng": 77.389849,
    "livelat": 28.6282231,
    "creditBalance": 127,
    "myCash": 10
}

我想更新“ creditBalance ”值并将 JSON 写入新文件。

private static void readJs(String path) throws IOException, JSONException {
    File file = new File(path);
    FileInputStream fis = new FileInputStream(file);
    byte[] buffer = new byte[(int) file.length()];
    fis.read(buffer);
    String json  = new String(buffer, StandardCharsets.UTF_8);
    JSONObject jsonObject = new JSONObject(json);
    jsonObject.put("creditBalance",78);                   //  <-  Updating a value
    FileWriter fw = new FileWriter("output.json");
    fw.write(jsonObject.toString());
}

标签: javajson

解决方案


您缺少关闭的文件编写器:

fw.close();

它必须关闭


推荐阅读