Question
What causes the java.io.StreamCorruptedException: invalid stream header error in Java and how can it be resolved?
// Java code that may trigger StreamCorruptedException
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"));
Object obj = ois.readObject();
Answer
The java.io.StreamCorruptedException occurs when an attempt to read a serialized object fails due to an invalid stream header. This typically signals that the data being read is not in the expected format, often because of mismatched serialization and deserialization methods or corrupt data.
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"))) {
Object obj = ois.readObject();
} catch (StreamCorruptedException e) {
System.out.println("Stream is corrupted: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO exception: " + e.getMessage());
}
Causes
- The data being read is not serialized in the expected ObjectStream format.
- The file being read was corrupted or altered after it was serialized.
- Using a different class version for serialization/deserialization than intended.
Solutions
- Ensure that the file being read was correctly serialized using ObjectOutputStream.
- Check for data corruption or use a different file that has valid serialized data.
- Make sure that the class definition matches the serialized version being deserialized.
Common Mistakes
Mistake: Attempting to deserialize data from a corrupted file without checking its integrity.
Solution: Verify that the file is intact and correctly serialized.
Mistake: Mismatching class versions leading to serialization issues.
Solution: Ensure that the class being deserialized matches the one used during serialization.
Helpers
- java io StreamCorruptedException
- invalid stream header
- fix StreamCorruptedException
- Java serialization error