cosmiczilch
cosmiczilch

Reputation: 43

Exception deserializing even simple objects [JAVA]

i have this relatively simple piece of Java (for Android) code which i have stripped down for this question.

int number = 42;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(number);
String serial = bos.toString("UTF-8");
os.close();

ByteArrayInputStream bis = new ByteArrayInputStream(serial.getBytes("UTF-8"));
ObjectInputStream is = new ObjectInputStream(bis);    // <<<< Exception Here

The last line, initializing the ObjectInputStream, throws a StreamCorruptedException and i have no idea why.

(i am planning to use this to serialize a few small objects to Strings and store them in SharedPreferences and read them back later. But i am using just an integer now because that isolates the problem)

Upvotes: 1

Views: 131

Answers (2)

Andreas Dolk
Andreas Dolk

Reputation: 114767

The problem lies within the conversion itself. We can't expect to get the same byte array back if we convert it to and from a string using a char encoding.

Simple example:

byte[] expected = { -1, -2, -3, -4, -5 };
byte[] actual = new String(expected).getBytes();

// actual is now [-17, -65, -67, -17, -65, -67, -17, -65, -67]

So if you want to store a bytes in a String, use Base64 encoding:

int number = 42;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(number);
String serial = new BASE64Encoder().encode(bos.toByteArray());
os.close();

ByteArrayInputStream bis = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(serial));
ObjectInputStream is = new ObjectInputStream(bis);

(Can't tell if that class is available on android. So you might have to look for a different implementation)

Upvotes: 2

Ren&#233; Link
Ren&#233; Link

Reputation: 51353

The problem is the bytes to string and vice versa conversion. Try the following and it should work:

int number = 42;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(number);
os.close();

byte[] serial = bos.toByteArray();

ByteArrayInputStream bis = new ByteArrayInputStream(serial);
ObjectInputStream is = new ObjectInputStream(bis); 

For details take a look at how to convert byte array to string and vice versa

Upvotes: 2

Related Questions