将JSON对象写入文件-附加功能不起作用

时间:2018-07-26 08:46:10

标签: java android json file-io streamwriter

我尝试将自定义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文件中。我的代码有什么问题 谢谢

0 个答案:

没有答案