我正在努力:
我可以找到这两个类,这就是我使用它们的方式。但是data[]
数组对我来说没有多大意义。为什么必须将一个空数组放入deserialize
方法?
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data)
throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
public static void main(String[] args) {
try {
Thing p = new Thing(2,4);
byte[]data = new byte[10240];
serialize(p);
Object des = deserialize(data);
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Pruebiña.class.getName())
.log(Level.SEVERE, null, ex);
}
}
我该如何解决这个问题?现在,当程序到达deserialize
行时,我遇到以下错误:
java.io.StreamCorruptedException: invalid stream header: 00000000
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
我该怎么做才能解决这个问题,并能够回写对象?是的,课程Thing
是Serializable
。
答案 0 :(得分:2)
您在serialize
中创建数组,不需要创建自己的数组。
这样做:
byte[] data = serialize(p);
而不是:
byte[]data = new byte[10240];
serialize(p);
答案 1 :(得分:2)
如果要写入文件,则根本不需要字节数组 FileInputStream和FileOutputStream例如。
public static void serialize(Object obj, File f) throws IOException {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f))) {
out.writeObject(obj);
}
}
public static Object deserialize(File f)
throws IOException, ClassNotFoundException {
try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(f))) {
return is.readObject();
}
}
static class Thing implements Serializable {
int a,b,c;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
File f = new File("object.dat");
Thing orig = new Thing();
serialize(orig, f);
Thing back = (Thing) deserialize(f);
}