0

I've looked at many places on serialization but can't seem to find a solution to my problem. I'm making an Email client program and I want to store every email I send as an object in a file and then be able to retrieve it.

The problem I encounter is that every time I use ObjectOutputStream's writeObject() method, it truncates the file instead of appending it. Then I tried storing the emails in an ArrayList and storing the ArrayList in the file. Like, everytime I want to store I would readObject() the ArrayList then add the new email to it and then write the ArrayList again to the file. But this method started throwing many exceptions(i.e InvalidClassException).

Is there a way to serialize objects such that I will be able to append them to the file each time I want to write a new email or any other workaround for this? Thanks in advance, below is the EmailMessage class:

public class EmailMessage implements Serializable{//implement serializables
    private String recipient;
    private String subject;
    private String content;
    private String date;

    public void setRecipient(String recipient)
    {
        this.recipient=recipient;
    }
    
    public String getRecipient()
    {
        return this.recipient;
    }
    
    public void setSubject(String subject){
        this.subject=subject;
    }

    public void setContent(String content){
        this.content=content;
    }

    public String getSubject(){
        return this.subject;
    }
    
    public String getContent(){
        return this.content;
    }

    public void setDate(String date)
    {
        this.date=date;
    }

    public String getDate()
    {
        return this.date;
    }

    public String printDetails()
    {
        String details="Recipient: "+getRecipient()+
                        "\nSubject: "+getSubject()+
                        "\nEmail content: "+getContent()+
                        "\nDate Sent: "+getDate(); 
        return details;
    }
}
JANO
  • 2,995
  • 2
  • 14
  • 29
scout
  • 11
  • 3
  • Please note i tried appending, by adding append to FileOutputStream constructor but turns to you can't append when using ObjectOutputStream. https://stackoverflow.com/questions/33620323/serializationjava-io-streamcorruptedexception-invalid-stream-header-0aaced00 – scout Aug 12 '22 at 11:07
  • Can you add the actual code storing the email into a file? Only with the email class nobody can reconstruct your problem, – JANO Aug 12 '22 at 11:21
  • Also, the Exception`s message could be helpful as – JANO Aug 12 '22 at 11:55

0 Answers0