aar*_*ell 3 java serialization
我正在尝试将对象序列化为Byte数组,以便存储在String中.我不能为我的生活找出我在这里出错的地方.
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);
}
Run Code Online (Sandbox Code Playgroud)
我一直在接受java.io.StreamCorruptedException,我不知道为什么:(
store = out.toString("UTF-8");
Run Code Online (Sandbox Code Playgroud)
输出的数据不是UTF-8格式的,实际上根本不是字符串.它是String的序列化实例.您可以在其上调用toString,因为您可以在任何对象上调用toString.
你想要的
byte [] data = out.toByteArray();
然后将数据传递给ByteArrayInputStream构造函数