简体   繁体   中英

How do I write objects via a byte buffer?

I'm trying to:

  • Write an object (or a series of objects of different types/classes) into a file
  • Read them back
  • Check the instances and cast them into objects of their same type/class again

I could find these two classes, and this is how I use them. But the data[] array doesn't make much sense to me. Why do you have to put an empty array of data into the deserialize method?

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

}

How can I fix this? Now I'm having the following error, when the program reaches the deserialize line:

java.io.StreamCorruptedException: invalid stream header: 00000000
     at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)

What can I do to fix this, and being able to write and read the objects back? And yes, the class Thing is Serializable .

You create the array in serialize , you don't need to create your own array.

Just do this:

    byte[] data = serialize(p);

Instead of this:

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

If you want to write to a File you don't need the byte arrays at all use FileInputStream and FileOutputStream eg.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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