Java 序列化

JDK 原生序列化

@Test
public void serializable() {
    try {
        ObjectOutputStream oos =
                new ObjectOutputStream(new FileOutputStream("./baozi.txt"));
        oos.writeObject(new User());
        oos.flush();
        oos.close();

        ObjectInputStream ois =
                new ObjectInputStream(new FileInputStream("./baozi.txt"));
        User user = (User) ois.readObject();
        ois.close();
        System.out.println(user.getName());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Protostuff序列化


   com.dyuproject.protostuff
   protostuff-runtime
   1.0.11


   com.dyuproject.protostuff
   protostuff-core
   1.0.11

import java.io.Serializable;
import java.util.Date;

/**
 * 区域信息
 */
public class Area implements Serializable {

    private static final long serialVersionUID = -6365039123188702005L;
    // ID
    private Integer areaId;
    // 名称
    private String areaName;
    // 权重
    private Integer priority;
    // 创建时间
    private Date createTime;
    // 更新时间
    private Date lastEditTime;

   // 省略get/set
}
序列化工具类: 
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.baozi.exception.SerializeException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class ProtostuffSerializer {

    /**
     * 序列化
     * @param obj
     * @param 
     * @return
     */
    public static  byte[] serialize(T obj) {
        if (obj == null) {
            throw new SerializeException("序列化对象(" + obj + ")为空!");
        }
        Schema schema = (Schema) RuntimeSchema.getSchema(obj.getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        byte[] result = null;
        try {
            result = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new SerializeException("序列化对象(" + obj + ")异常!");
        } finally {
            buffer.clear();
        }
        return result;
    }

    /**
     * 反序列化
     * @param bytes
     * @param targetClass
     * @param 
     * @return
     */
    public static  T deserialize(byte[] bytes, Class targetClass) {
        if (bytes == null || bytes.length == 0) {
            throw new SerializeException("反序列化对象发生异常,byte序列为空!");
        }
        Schema schema = RuntimeSchema.getSchema(targetClass);
        T result = schema.newMessage();
        try {
            ProtostuffIOUtil.mergeFrom(bytes, result, schema);
        } catch (Exception e) {
            throw new SerializeException("反序列化失败");
        }
        return result;
    }

    /**
     * 序列化集合
     * @param objList
     * @param 
     * @return
     */
    public static  byte[] serializeList(List objList) {
        if (objList == null || objList.isEmpty()) {
            throw new SerializeException("序列化集合(" + objList + ")为空!");
        }
        Schema schema = (Schema) RuntimeSchema.getSchema(objList.get(0).getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        byte[] result = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer);
            result = bos.toByteArray();
        } catch (Exception e) {
            throw new SerializeException("序列化对象(" + objList + ")异常!");
        } finally {
            buffer.clear();
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 反序列化集合
     * @param bytes
     * @param targetClass List中的T的类型
     * @param 
     * @return
     */
    public static  List deserializeList(byte[] bytes, Class targetClass) {
        if (bytes == null || bytes.length == 0) {
            throw new SerializeException("反序列化对象发生异常,byte序列为空!");
        }
        Schema schema = RuntimeSchema.getSchema(targetClass);
        List result = null;
        try {
            result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(bytes), schema);
        } catch (IOException e) {
            throw new SerializeException("反序列化失败");
        }
        return result;
    }

}
@Test
public void serializeStr() {
    // 序列化
    byte[] temp = ProtostuffSerializer.serialize("ABC");

    // 反序列化
    String result = ProtostuffSerializer.deserialize(temp, String.class);
    System.out.println(result);
}

@Test
public void serializeObj() {
    // 序列化
    Area area = new Area();
    area.setAreaName("baozi");
    byte[] temp = ProtostuffSerializer.serialize(area);

    // 反序列化
    Area result = ProtostuffSerializer.deserialize(temp, Area.class);
    System.out.println(result.getAreaName());
}

@Test
public void serializeList() {
    // 序列化
    List areaList = new ArrayList<>();
    Area area = new Area();
    area.setAreaName("baozi");
    areaList.add(area);
    byte[] temp = ProtostuffSerializer.serializeList(areaList);

    // 反序列化
    List result = ProtostuffSerializer.deserializeList(temp, Area.class);
    System.out.println(result.get(0).getAreaName());
}

你可能感兴趣的:(Java 序列化)