java - 将 JSON 对象写入文件 - 附加不起作用
问题描述
我尝试将我的自定义 JSONObject 保存到文件中。一切正常,但我无法将 json 附加到文件中。例如,如果我单击两次以保存 json,在我的文件中我有一个元素。这是我的来源
public class TransactionFileManager {
public static final File path = Environment.
getExternalStoragePublicDirectory(Environment.getExternalStorageState() + "/myfolder/");
public static final File file = new File(path, "transaction1.json");
public static String read() {
String ret = null;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try {
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
bufferedReader.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return ret;
}
public static void writeToFile(JSONObject data) {
if (!path.exists()) {
path.mkdirs();
}
try {
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);
outputStreamWriter.append(data.toString());
outputStreamWriter.close();
fOut.flush();
fOut.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
}
我如何将 json 对象附加到我的 .json 文件中。我的代码有什么问题谢谢
解决方案
推荐阅读
- python - 有什么方法可以将向量转换为欧拉角?
- git - 合并MR时Gitlab CI运行作业
- python - 通用 *args 的 Python 类型提示(特别是 zip 或 zipWith)
- javascript - 如何在 VueJs 中制作表格并在 .NET Core Web 应用程序中添加 MSSQL 数据库接收的值
- azure-devops - 是否允许从 Azure-Devops 与我的数据中心建立 VPN 连接?
- python - 列表理解输出
- python - Matplotlib 动画擦除以前的数据
- javascript - 如何修复页面加载时音频不自动播放的问题?- html
- amazon-web-services - Cloudformation 自定义资源
- vba - 是否可以在 VBA 中使用 MyServices.ClipboardProxy?