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序列化

<dependency>
   <groupId>com.dyuproject.protostuff</groupId>
   <artifactId>protostuff-runtime</artifactId>
   <version>1.0.11</version>
</dependency>
<dependency>
   <groupId>com.dyuproject.protostuff</groupId>
   <artifactId>protostuff-core</artifactId>
   <version>1.0.11</version>
</dependency>
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 <T>
     * @return
     */
    public static <T> byte[] serialize(T obj) {
        if (obj == null) {
            throw new SerializeException("序列化对象(" + obj + ")为空!");
        }
        Schema<T> schema = (Schema<T>) 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 <T>
     * @return
     */
    public static <T> T deserialize(byte[] bytes, Class<T> targetClass) {
        if (bytes == null || bytes.length == 0) {
            throw new SerializeException("反序列化对象发生异常,byte序列为空!");
        }
        Schema<T> 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 <T>
     * @return
     */
    public static <T> byte[] serializeList(List<T> objList) {
        if (objList == null || objList.isEmpty()) {
            throw new SerializeException("序列化集合(" + objList + ")为空!");
        }
        Schema<T> schema = (Schema<T>) 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>中的T的类型
     * @param <T>
     * @return
     */
    public static <T> List<T> deserializeList(byte[] bytes, Class<T> targetClass) {
        if (bytes == null || bytes.length == 0) {
            throw new SerializeException("反序列化对象发生异常,byte序列为空!");
        }
        Schema<T> schema = RuntimeSchema.getSchema(targetClass);
        List<T> 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<Area> areaList = new ArrayList<>();
    Area area = new Area();
    area.setAreaName("baozi");
    areaList.add(area);
    byte[] temp = ProtostuffSerializer.serializeList(areaList);

    // 反序列化
    List<Area> result = ProtostuffSerializer.deserializeList(temp, Area.class);
    System.out.println(result.get(0).getAreaName());
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容