如何通过字节缓冲区写入对象?

时间:2015-09-04 02:11:37

标签: java serialization deserialization

我正在努力:

  • 将对象(或一系列不同类型/类的对象)写入文件
  • 阅读它们
  • 检查实例并将它们再次转换为相同类型/类的对象

我可以找到这两个类,这就是我使用它们的方式。但是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)

我该怎么做才能解决这个问题,并能够回写对象?是的,课程ThingSerializable

2 个答案:

答案 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);
}