首页 > 解决方案 > 将 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 文件中。我的代码有什么问题谢谢

标签: javaandroidjsonfile-iostreamwriter

解决方案


推荐阅读