甚至反序列化甚至简单对象[JAVA]

时间:2013-07-06 20:49:53

标签: java android serialization deserialization

我有这个相对简单的Java(对于Android)代码,我已经删除了这个问题。

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

最后一行,初始化ObjectInputStream,抛出StreamCorruptedException,我不明白为什么。

(我打算用它来将一些小对象序列化为Strings并将它们存储在SharedPreferences中并稍后再读回来。但我现在只使用一个整数,因为这会隔离问题)

2 个答案:

答案 0 :(得分:2)

问题是要字符串的字符串,反之亦然。 尝试以下操作,它应该可以工作:

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); 

有关详细信息,请查看how to convert byte array to string and vice versa

答案 1 :(得分:2)

问题在于转换本身。如果我们使用char编码将它转换为字符串或从字符串转换,我们不能期望获得相同的字节数组。

简单示例:

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]

因此,如果要在String中存储字节,请使用Base64编码:

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);

(无法判断该类是否在Android上可用。所以你可能需要寻找不同的实现)

相关问题