英文:
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.
{
"id": 4051,
"name": "menad",
"livelng": 77.389849,
"livelat": 28.6282231,
"creditBalance": 127,
"myCash": 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("creditBalance",78); // <- Updating a value
FileWriter fw = new FileWriter("output.json");
fw.write(jsonObject.toString());
}
答案1
得分: 1
你缺少了关闭文件写入器:
fw.close();
它必须关闭。
英文:
You lacked close filewriter:
fw.close();
It have to close
答案2
得分: 0
可以选择以下方法之一:
- 在您的FileWriter对象上调用
flush()
方法,这将导致它实际上写出其缓冲区的内容,或者 - 调用
close()
方法来关闭FileWriter,在关闭之前会自动执行刷新操作。
如果您已经完成向该特定文件的写入,选项2是最佳选择。当您完成对资源(如文件)的操作时,务必小心关闭这些资源。
英文:
You can either:
- Call the
flush()
method on your FileWriter object, which will cause it to actually write out the contents of its buffer, or - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论