Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Serialization Pains (java.io.StreamCorruptedException)

I'm trying to Serialize an object to a Byte array, for storage in a String. I cannot for the life of me figure out where I'm going wrong here.

String store = null;

// Writing
try {
    String hi = "Hi there world!";
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeObject(hi);
    oos.close();

    store = out.toString("UTF-8");
} catch(Exception e) {
    System.out.println(e);
}

// Reading
try {
    ByteArrayInputStream in = new ByteArrayInputStream(store.getBytes("UTF-8"));
    ObjectInputStream ois = new ObjectInputStream(in);

    String data = (String) ois.readObject();
} catch(Exception e) {
    System.out.println(e);
}

I keep getting java.io.StreamCorruptedException and I don't know why :(

like image 890
aaronsnoswell Avatar asked Sep 25 '26 23:09

aaronsnoswell


2 Answers

store = out.toString("UTF-8");

the data in out is not UTF-8 formatted, in fact it's not a String at all. It's a serialized instance of a String. You can call toString on it, just because you can call toString on any object.

you'd want to to

byte[] data = out.toByteArray();

and then pass data into the ByteArrayInputStream constructor

like image 200
MeBigFatGuy Avatar answered Sep 28 '26 13:09

MeBigFatGuy


Unfortunatelly, Java strings aren't an array of bytes (as in C), but rather an array of chars (16-bit values). Also, all strings are unicode in Java.

My best advice is: use Base64 encoding/decoding if you need to store binary data into strings. Apache Commons has some great classes for this task, and you can find more info at:

http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html

like image 41
Robson França Avatar answered Sep 28 '26 13:09

Robson França



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!