I am attempting to save multiple objects into a file by running the code multiple times. But in the second run, I get a java.io.StreamCorruptedException error.
package BinaryIO;
import java.io.*;
public class OOSDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
File file = new File("src/BinaryIO/robotData.dat");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file, true))) {
oos.writeObject(new Robot());
oos.flush();
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
while (true) {
try {
System.out.println(ois.readObject().toString());
} catch (EOFException e) {
break;
}
}
}
}
}
class Robot implements Serializable {
int x, y;
String model;
public Robot() {
this(0, 0, "Default");
}
public Robot(int x, int y, String model) {
this.x = x;
this.y = y;
this.model = model;
}
@Override
public String toString() {
return String.format("Robot: (%d, %d), Model: %s", x, y, model);
}
}
Error in the second run:
Robot: (0, 0), Model: Default
Exception in thread "main" java.io.StreamCorruptedException: invalid type code: AC
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1743)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:519)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:477)
at BinaryIO.OOSDemo.main(OOSDemo.java:14)
I am not able to identify the problem. On online forums, it says that the error could occur if:
- you try to open an ObjectInputStream around some data that wasn't actually written using an ObjectOutputStream;
- during a readObject() operation, the stream gets in the "wrong place". [Source]