Object before = "";
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(os);
oo.writeObject(before);
oo.close();
String serialized = os.toString("UTF-8");
ByteArrayInputStream is = new ByteArrayInputStream(serialized.getBytes("UTF-8"));
try(ObjectInputStream io = new ObjectInputStream(is)) {
Object after = io.readObject();
System.err.println("Object deserialization successful.");
} catch (Exception e) {
System.err.println("Object deserialization error.");
System.err.println("Type being serialized: " + before.getClass());
System.err.println("Serialization as bytes: " + Arrays.toString(serialized.getBytes("UTF-8")));
e.printStackTrace();
}
So I've got a bit of code I'm working with that's supposed to serialize an object to a java.lang.String and deserialize it later. I'm using object streams to do the object writing/reading and byte array streams to do the string handling. But when I try to construct an ObjectInputStream around the serialized object, I get a StreamCorruptedException, claiming there's an "invalid stream header".
The code sample above is the most basic piece of code I could find that reproduces my issue (and it's pretty simple!). As far as I can tell, I'm doing everything perfectly symmetrically:
- Make an ObjectOutputStream around a ByteArrayOutputStream
- Write a (simple!) object to the OOS
- Get a UTF-8 String from the BAOS
- Make an ObjectInputStream around a ByteArrayInputStream around that String's UTF-8 bytes
- Read an object from the OIS
But at step 4, during ObjectInputStream's constructor the program crashes with a StreamCorruptedException. I'm extremely confused by that, given that the bytes were literally just produced by an ObjectOutputStream!
Don't convert the
byte[]
to and from aString
, that is going to interpret special (wide) characters. Instead, just use the bytes from theByteArrayOutputStream
directly. Like,