java - 修改一个值并将 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());
}
解决方案
您缺少关闭的文件编写器:
fw.close();
它必须关闭
推荐阅读
- assembly - Gameboy 旋转指令
- python - 相当于 python 中的 matlab bwconncomp 和 regionprops
- python - rosrun错误找不到可执行文件和CMake错误
- java - JUnit 5 with Spring boot - 如何使用不同的配置文件重复测试?
- javascript - 从数组中删除值不起作用 NEXT.JS
- python - Python 备份脚本上的 BrokenPipeError
- javascript - 如何从javascript设置数据值
- image - 我有 3 张图像,我想使用 subplot 将它们显示在 1 个图中,但是它们太小了,我怎样才能使它们更大更清晰?
- git - 为什么要更改所有父 ref 的分离头状态的新分支?
- javascript - React - TypeError:无法读取未定义的属性“smallThumbnail”