代码之家  ›  专栏  ›  技术社区  ›  BekaKK

将JSON对象写入文件-追加无效

  •  0
  • BekaKK  · 技术社区  · 6 年前

    我尝试将我的自定义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 回复  |  直到 6 年前