数据序列化与反序列化

public class SerializerUtil {
    /**
     * 序列化
     * 
     * @param object
     * @return
     */
    public static byte[] serializeObj(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            throw new RuntimeException("序列化失败!", e);
        }
    }
 
    public static void main(String[] args) {
        Man m = new Man();
        m.setAge(121223);
        m.setId(35135334L);
        m.setName("zhangsan");
        byte[] serializeObj = SerializerUtil.serializeObj(m);
 
        Man deserializeObj = (Man) deserializeObj(serializeObj);
        System.out.println(deserializeObj.getAge());
        System.out.println(deserializeObj.getName());
        System.out.println(deserializeObj.getId());
    }
 
    /**
     * 反序列化
     * 
     * @param bytes
     * @return
     */
    public static Object deserializeObj(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException("反序列化失败!", e);
        }
    }
}

 

你可能感兴趣的:(JAVA)