Java Serializable Object to Byte Array

后端 未结 12 1305
春和景丽
春和景丽 2020-11-22 03:12

Let\'s say I have a serializable class AppMessage.

I would like to transmit it as byte[] over sockets to another machine where it is rebuil

12条回答
  •  长情又很酷
    2020-11-22 03:31

    I also recommend to use SerializationUtils tool. I want to make a ajust on a wrong comment by @Abilash. The SerializationUtils.serialize() method is not restricted to 1024 bytes, contrary to another answer here.

    public static byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            oos.flush();
        }
        catch (IOException ex) {
            throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
        }
        return baos.toByteArray();
    }
    

    At first sight, you may think that new ByteArrayOutputStream(1024) will only allow a fixed size. But if you take a close look at the ByteArrayOutputStream, you will figure out the the stream will grow if necessary:

    This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().

提交回复
热议问题