java.io.StreamCorruptedException: formato incorreto ao ler mais de 1 objeto [duplicado]

Esta pergunta já tem uma resposta aqui:

Stre, amCorruptedException: código de tipo inválido: AC 1 resposta

Estou tentando adicionar um objeto (deOneChatMessage classe) em um arquivo a cada clique do botão. E então eu tento ler todos os objetos do arquivo e carregá-lo em umArrayList. Mas eu recebo umStreamCorruptedException na segunda iteração deObjectInputStream.readObject() na função de desserialização. Eu verifiquei que a primeira iteração funciona bem.

Eu li muitos outros posts sobre o mesmo problema:

Uma sugestão (Desserializar vários objetos Java) é escrever a lista inteira da matriz no arquivo em vez de objetos individuais. Mas isso parece um desperdício, pois eu preciso gravar em um arquivo a cada clique e haveria centenas de objetos ao longo do tempo.Outra sugestão (StreamCorruptedException: código de tipo inválido: AC) tem a ver com diferentes cabeçalhos criados por ObjectOutputStream. Não tenho ideia de quem usar esse conhecimento para resolver o problema.

Alguma idéia de como posso resolver isso?

OneChatMessage.java:

package com.slapp.chat;

import java.io.Serializable;
import java.util.Date;

import com.slapp.localDB.Contact;

//This class defines the class for a chat message
public class OneChatMessage implements Serializable{
    private String text;
    private Date timeSent;
    private Boolean sentByMe;

    public OneChatMessage(String text, Date timeSent, Boolean sentByMe){
        this.text = text;
        this.timeSent = timeSent;
        this.sentByMe = sentByMe;
    }

    public String getText(){
        return this.text;
    }

    public Date getTimeSent(){
        return this.timeSent;
    }

    @Override
    public String toString(){
        return new StringBuffer(" Text : ")
        .append(this.text)
        .append(" TimeSent : ")
        .append(this.timeSent.toString()) // Need to use SimpleDatFormat to get the correct time zone and formatting. Leaving it for now.
        .append(" SentByMe : ")
        .append(this.sentByMe.toString()).toString();
    }
}

Função de serialização:

public void addMessage(OneChatMessage msg) {
        FileOutputStream fos;
        ObjectOutputStream oos;

        File file = new File(context.getFilesDir(), "abc");
        if (!file.exists()) {
            Log.d("faizal",
                    "The file does not exist : ");
        } else {
            Log.d("faizal",
                    "The file already exists : ");
        }
        try {

            fos = context.openFileOutput("abc",
                    Context.MODE_APPEND);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(msg);
            oos.close();
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d("faizal", "file not found : ");
            e.printStackTrace();
        } catch (IOException e) {
            Log.d("faizal", "Error closing file : ");
            e.printStackTrace();
        }
}

Função desserializante:

public ArrayList<OneChatMessage> getAllChatMessagesArrayList() {
        ArrayList<OneChatMessage> chatMessages = new ArrayList<OneChatMessage>();
        OneChatMessage oneChatMsg;
        FileInputStream fis;
        ObjectInputStream ois;

        try {

            fis = context.openFileInput("abc");
            ois = new ObjectInputStream(fis);
            //Setting an arbitrarily large number as the limit of the loop iterations
            //so that chat message are read from the file till EOF
            for (int i = 1; i < 999999999; i++) {
                try {
                    oneChatMsg = (OneChatMessage) ois.readObject();
                } catch (EOFException e) {
                    //When EOFException occurs, quit the loop
                    break;
                }

                try{
                    chatMessages.add(oneChatMsg);
                } catch(Exception e){
                    Log.d("faizal","Error adding message to Array List:" + oneChatMsg.getText());
                    e.printStackTrace();
                }


            }
            ois.close();
            fis.close();

            return chatMessages;
        } catch (FileNotFoundException e) {
            Log.d("faizal", "The file not found : ");
            e.printStackTrace();
        } catch (IOException e) {
            Log.d("faizal", "Error closing file : ");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            Log.d("faizal","Error reading object from file : ");
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            Log.d("faizal", "Error adding object to array list from file : ");
            e.printStackTrace();
        }
        return null; // in case there was a caught exception

    }

Logcat:

05-27 16:56:17.576: W/System.err(25028): java.io.StreamCorruptedException: Wrong format: ac
05-27 16:56:17.576: W/System.err(25028):    at java.io.ObjectInputStream.corruptStream(ObjectInputStream.java:701)
05-27 16:56:17.576: W/System.err(25028):    at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:814)
05-27 16:56:17.576: W/System.err(25028):    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2006)
05-27 16:56:17.576: W/System.err(25028):    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1963)
05-27 16:56:17.576: W/System.err(25028):    at com.slapp.chat.ChatPersistenceHandler.getAllChatMessagesArrayList(ChatPersistenceHandler.java:62)
05-27 16:56:17.576: W/System.err(25028):    at com.example.slapp.ChatSessionActivity$ChatArrayAdapter.<init>(ChatSessionActivity.java:178)
05-27 16:56:17.576: W/System.err(25028):    at com.example.slapp.ChatSessionActivity.onCreate(ChatSessionActivity.java:86)
05-27 16:56:17.576: W/System.err(25028):    at android.app.Activity.performCreate(Activity.java:5372)
05-27 16:56:17.576: W/System.err(25028):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread.access$700(ActivityThread.java:168)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
05-27 16:56:17.576: W/System.err(25028):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-27 16:56:17.576: W/System.err(25028):    at android.os.Looper.loop(Looper.java:137)
05-27 16:56:17.576: W/System.err(25028):    at android.app.ActivityThread.main(ActivityThread.java:5493)
05-27 16:56:17.576: W/System.err(25028):    at java.lang.reflect.Method.invokeNative(Native Method)
05-27 16:56:17.576: W/System.err(25028):    at java.lang.reflect.Method.invoke(Method.java:525)
05-27 16:56:17.576: W/System.err(25028):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
05-27 16:56:17.576: W/System.err(25028):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
05-27 16:56:17.576: W/System.err(25028):    at dalvik.system.NativeStart.main(Native Method)

questionAnswers(1)

yourAnswerToTheQuestion