I'm trying to append objects to a serialized file but when I read it, it only contains the most recent object instead of all of the objects:
import java.io.*;
public class Main implements Serializable {
public static void main(String[] args) throws IOException, ClassNotFoundException {
TestClass test = new TestClass();
test.username = "this one is second";
test.age = 23;
test.phone = "+1 (010) 000 0000";
test.address = "2 Main St.";
TestClass test2 = new TestClass();
test2.username = "this one is second 22222";
test2.age = 23;
test2.phone = "+1 (010) 000 0000";
test2.address = "2 Main St.";
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Java Projects\\ObjectOutputStreamTests\\files\\test.ser"));
out.writeObject(test);
out.writeObject(test2);
out.close();
ObjectOutputStream out2 = new ObjectOutputStream(new FileOutputStream("C:\\Java Projects\\ObjectOutputStreamTests\\files\\test.ser", true)) {
@Override
protected void writeStreamHeader() throws IOException {
reset();
}
};
out2.writeObject(test);
out2.writeObject(test2);
out2.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Java Projects\\ObjectOutputStreamTests\\files\\test.ser"));
try {
while ((in.readObject()) != null) {
TestClass testRead = (TestClass) in.readObject();
System.out.println(testRead.username);
System.out.println(testRead.age);
System.out.println(testRead.address);
System.out.println(testRead.phone);
}
} catch (EOFException e) {
System.out.println("end");
}
}
}
TestClass:
import java.io.Serializable;
public class TestClass implements Serializable {
public String username;
public int age;
public String phone;
public String address;
}
When I run this code, I get the second object (test2) printed twice, instead of the first and second object consecutively. This issue persists with more or less objects. How do I fix this?