Java 修改值并将JSON写入文件

Java 修改值并将JSON写入文件,java,json,Java,Json,我试图修改JSON并将修改后的JSON写入文件。但是写入JSON的输出文件是空的 { "id": 4051, "name": "menad", "livelng": 77.389849, "livelat": 28.6282231, "creditBalance": 127, "myCash": 10 } 我

我试图修改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());
}
private static void readJs(字符串路径)抛出IOException、jsoneexception{
文件=新文件(路径);
FileInputStream fis=新的FileInputStream(文件);
byte[]buffer=新字节[(int)file.length()];
fis.read(缓冲区);
String json=新字符串(缓冲区,StandardCharsets.UTF_8);
JSONObject JSONObject=新的JSONObject(json);

jsonObject.put(“creditBalance”,78);//您缺少关闭的filewriter:

fw.close()

它必须关闭

您可以:

  • 在FileWriter对象上调用
    flush()
    方法,这将导致它实际写出其缓冲区的内容,或者
  • 调用
    close()
    方法关闭FileWriter,这将导致它在关闭前自动刷新

  • 如果您已完成对此特定文件的写入,则选项2是最佳选择。在完成对资源(如文件)的操作后,应始终小心关闭这些资源。

    您是否尝试关闭该文件?如果写入程序已关闭,您需要刷新应自动发生的更改。谢谢,它起到了作用。