我有一段相对简单的 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,我不知道为什么。
(我打算用它来将一些小对象序列化为字符串,并将它们存储在 SharedPreferences 中,稍后再读回它们。但我现在只使用一个整数,因为这样可以隔离问题)
最佳答案
问题在于转换本身。如果我们使用 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]
所以如果你想在字符串中存储一个字节,使用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 上可用。因此您可能需要寻找不同的实现)
关于java - 异常反序列化甚至简单的对象[JAVA],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17507014/