修改一个值并将JSON写入文件

huangapple go评论68阅读模式
英文:

Modify a value and write JSON to a file

问题

我正试图修改一个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); //  <- 更新数值
    FileWriter fw = new FileWriter("output.json");
    fw.write(jsonObject.toString());
}
英文:

I am trying to modify a JSON and write the modified JSON to a file. But the output file to which JSON was written was empty.

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

I want to update "creditBalance" value and write the JSON to a new File.

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(&quot;creditBalance&quot;,78);                   //  &lt;-  Updating a value
    FileWriter fw = new FileWriter(&quot;output.json&quot;);
    fw.write(jsonObject.toString());
}

答案1

得分: 1

你缺少了关闭文件写入器:

fw.close();

它必须关闭。

英文:

You lacked close filewriter:

fw.close();

It have to close

答案2

得分: 0

可以选择以下方法之一:

  1. 在您的FileWriter对象上调用flush()方法,这将导致它实际上写出其缓冲区的内容,或者
  2. 调用close()方法来关闭FileWriter,在关闭之前会自动执行刷新操作。

如果您已经完成向该特定文件的写入,选项2是最佳选择。当您完成对资源(如文件)的操作时,务必小心关闭这些资源。

英文:

You can either:

  1. Call the flush() method on your FileWriter object, which will cause it to actually write out the contents of its buffer, or
  2. Call the close() method to close the FileWriter, which will cause it to flush automatically before closing.

Option 2 is the best choice if you are finished writing to this particular file. You should always be careful to close resources (like files) when you've completed operating on them.

huangapple
  • 本文由 发表于 2020年9月17日 21:35:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63939274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定