Rumesh Madhusanka
Rumesh Madhusanka

Reputation: 1415

Serializing and deserializing same object doesn't reflect its change of state

When I tried to serialize an object the to deserialize it multiple times. In the first attempts it works fine. But from the second time I run the above code changing objects' attributes, they are not changed in the file. Neither overridden nor appended.

import java.io.*;
import java.util.ArrayList;

public class FileWrite {
static String es="EmailSave.txt";

    public static void writeTo(String name, String line) throws IOException {
        File OfficeRes = new File(name);
        BufferedWriter bw = new BufferedWriter(new FileWriter(OfficeRes, true));
        bw.append(line);
        bw.append("\n");
        bw.close();
    }

    public static void serializeTo(String file, Serializable s) throws IOException {
        FileOutputStream f = new FileOutputStream(file, true);
        ObjectOutputStream os = new ObjectOutputStream(f);
        os.writeObject(s);
        os.close();
    }

    public static Object deserializeFrom(String file) throws IOException, ClassNotFoundException {
        //assumption: file only has one serialized object
        FileInputStream f = new FileInputStream(file);
        ObjectInputStream obj = new ObjectInputStream(f);

        Object a=obj.readObject();
        obj.close();
        return a;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        OfficialRecipient a1=new OfficialRecipient();
        OfficialFriend a2=new OfficialFriend();
        PersonalRecipient a3=new PersonalRecipient();
        OfficialFriend a4=new OfficialFriend();
        a4.designation="tghfgbrb";
        a3.name="bhuvuycghchg";
        a1.email="bygygygyg";
        ArrayList<Recipient> a=new ArrayList<>();
        a.add(a1);
        a.add(a2);
        a.add(a3);
        a.add(a4);
        serializeTo(es, a);
        System.out.println(deserializeFrom(es));
    }

}

Upvotes: 0

Views: 258

Answers (1)

D.B.
D.B.

Reputation: 4713

The problem is you're appending to the output file rather than overwriting. Then when you read from the file you're getting the first object, which is the oldest one.

When you do this: new FileWriter(file, true) the second parameter true is causing the FileWriter to append to the file.

You need to use false as the second parameter so that each time you run it will overwrite the data in the file rather than appending:

new FileOutputStream(file, false);

Upvotes: 1

Related Questions