java序列化和反序列化kryo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_29843547/article/details/74518859

概念介绍

把Java对象转换为字节序列的过程称为对象的序列化。
把字节序列恢复为Java对象的过程称为对象的反序列化。

对象的序列化主要有两种用途:
  1) 数据介质存储
  2) 数据网络传输
1)对象序列化–java

public byte[] serialize(Object obj) throws Exception {  
    if(obj==null) throw new NullPointerException();  

    ByteArrayOutputStream os = new ByteArrayOutputStream();  
    ObjectOutputStream out = new ObjectOutputStream(os);  
    out.writeObject(obj);  
    return os.toByteArray();  
}  

public Object deserialize(byte[] by) throws Exception {  
    if(by==null) throw new NullPointerException();  

    ByteArrayInputStream is = new ByteArrayInputStream(by);  
    ObjectInputStream in = new ObjectInputStream(is);  
    return in.readObject();  
}  

2)对象序列化–hessian
public byte[] serialize(Object obj) throws IOException{
if(obj==null) throw new NullPointerException();

ByteArrayOutputStream os = new ByteArrayOutputStream();  
HessianOutput ho = new HessianOutput(os);  
ho.writeObject(obj);  
return os.toByteArray();  

}

public Object deserialize(byte[] by) throws IOException{
if(by==null) throw new NullPointerException();

ByteArrayInputStream is = new ByteArrayInputStream(by);  
HessianInput hi = new HessianInput(is);  
return hi.readObject();  

}
3)对象序列化–kryo

/**
     * Kryo serialize
     *
     * @param source
     * @return
     * @throws IOException
     */
    public static byte[] KryoSerialize(Object source) throws IOException {

        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            Kryo kryo = new Kryo();
            Output output = new Output(bos);
            kryo.writeObject(output, source);
            output.flush();
            output.close();
            return bos.toByteArray();
        } finally {
            try {
                bos.close();
            } catch (IOException e) {
                log.warn("IOException while kryoWriteObject final:", e);
            }
        }
    }

    /**
     * Kryo deserialize
     *
     * @param bytes,Class
     * @return
     * @throws IOException
     */
    public static <T> T KryoDeserialize(byte[] bytes, Class<T> type) throws IOException {
        if (bytes == null) {
            return null;
        }
        Kryo kryo = new Kryo();
        Input input = new Input(bytes);
        T obj = kryo.readObject(input, type);
        input.close();
        return obj;
    }

    public static void main(String[] args) throws IOException {
        System.out.println("start");
        byte[] ser = KryoSerialize(1L);
        System.out.println("KryoSerialize=====" + new String(ser));
        System.out.println("KryoDeserialize=====" + KryoDeserialize(ser, Long.class));
    }

猜你喜欢

转载自blog.csdn.net/sinat_29843547/article/details/74518859