繁体   English   中英

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

[英]How do I write objects via a byte buffer?

我试着:

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

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

您在serialize创建数组,您不需要创建自己的数组。

这样做:

    byte[] data = serialize(p);

而不是这个:

    byte[]data = new byte[10240];
    serialize(p);

如果要写入文件,则根本不需要字节数组,例如使用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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM