Java Serializable Object to Byte Array

后端 未结 12 1287
春和景丽
春和景丽 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:33

    In case you want a nice no dependencies copy-paste solution. Grab the code below.

    Example

    MyObject myObject = ...
    
    byte[] bytes = SerializeUtils.serialize(myObject);
    myObject = SerializeUtils.deserialize(bytes);
    

    Source

    import java.io.*;
    
    public class SerializeUtils {
    
        public static byte[] serialize(Serializable value) throws IOException {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
    
            try(ObjectOutputStream outputStream = new ObjectOutputStream(out)) {
                outputStream.writeObject(value);
            }
    
            return out.toByteArray();
        }
    
        public static  T deserialize(byte[] data) throws IOException, ClassNotFoundException {
            try(ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
                //noinspection unchecked
                return (T) new ObjectInputStream(bis).readObject();
            }
        }
    }
    

提交回复
热议问题