Java序列化难题(Java.io.StreamCorruptedException)
我试图将一个对象序列化为一个字节数组,以便以字符串形式存储。我一辈子都搞不清楚我到底出了什么错Java序列化难题(Java.io.StreamCorruptedException),java,serialization,Java,Serialization,我试图将一个对象序列化为一个字节数组,以便以字符串形式存储。我一辈子都搞不清楚我到底出了什么错 String store = null; // Writing try { String hi = "Hi there world!"; ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.w
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);
}
我不断得到java.io.StreamCorruptedException
,我不知道为什么:(
输入输出的数据不是UTF-8格式,事实上它根本不是字符串。它是字符串的序列化实例。您可以对其调用toString,因为您可以对任何对象调用toString
你会想的
字节[]数据=out.toByteArray()
然后将数据传递到ByteArrayInputStream构造函数中。如果要将字节数组保存为字符串,则需要将其转换为Base64字符串,而不是UTF-8字符串。为此,可以使用。此外,所有字符串在Java中都是unicode 我最好的建议是:如果需要将二进制数据存储到字符串中,请使用Base64编码/解码。Apache Commons有一些很好的类可用于此任务,您可以在以下位置找到更多信息:
问题在于,序列化时的初始字符串是一个序列化字符串。这与将字符串切碎为其组成字符的数组不同。我建议使用以下代码: 请注意,“ISO-8859-1”编码保留字节数组,而“UTF-8”则不保留(某些字节数组导致此编码中的字符串无效)
/**
*序列化任何对象
*@param obj
*@返回
*/
公共静态字符串序列化(对象obj){
试一试{
ByteArrayOutputStream bo=新建ByteArrayOutputStream();
ObjectOutputStream so=新的ObjectOutputStream(bo);
so.writeObject(obj);
所以,flush();
//这种编码在字节[]和字符串之间产生双射(与UTF-8不同)
返回bo.toString(“ISO-8859-1”);
}捕获(例外e){
e、 printStackTrace();
}
}
/**
*反序列化任何对象
*@param str
*@param-cls
*@返回
*/
公共静态T反序列化(字符串str,类cls){
//反序列化对象
试一试{
//这种编码在字节[]和字符串之间产生双射(与UTF-8不同)
字节b[]=str.getBytes(“ISO-8859-1”);
ByteArrayInputStream bi=新的ByteArrayInputStream(b);
ObjectInputStream si=新ObjectInputStream(bi);
返回cls.cast(si.readObject());
}捕获(例外e){
e、 printStackTrace();
}
}
感谢您的回答,我现在使用Base64编码工作,尽管因为我的目标是Androidstore = out.toString("UTF-8");
/**
* Serialize any object
* @param obj
* @return
*/
public static String serialize(Object obj) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(obj);
so.flush();
// This encoding induces a bijection between byte[] and String (unlike UTF-8)
return bo.toString("ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Deserialize any object
* @param str
* @param cls
* @return
*/
public static <T> T deserialize(String str, Class<T> cls) {
// deserialize the object
try {
// This encoding induces a bijection between byte[] and String (unlike UTF-8)
byte b[] = str.getBytes("ISO-8859-1");
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
return cls.cast(si.readObject());
} catch (Exception e) {
e.printStackTrace();
}
}