Java serialize and immediately deserialize gives error

879 Views Asked by At
    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:

  1. Make an ObjectOutputStream around a ByteArrayOutputStream
  2. Write a (simple!) object to the OOS
  3. Get a UTF-8 String from the BAOS
  4. Make an ObjectInputStream around a ByteArrayInputStream around that String's UTF-8 bytes
  5. 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!

1

There are 1 best solutions below

0
On

Don't convert the byte[] to and from a String, that is going to interpret special (wide) characters. Instead, just use the bytes from the ByteArrayOutputStream directly. Like,

ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());