java对象转数组|数组转对象

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cc.xx.mall.common.assertion.Assert;
import cc.xx.mall.common.tools.CompressUtil;

/**
 * 对象转bytes和bytes转对象
 * 
 * @project order
 * @fileName ByteUtil.java
 * @Description
 * @author light-zhang
 * @date 2019年5月16日
 * @version 1.0.0
 */
public class ByteUtil {
    /**
     * 对象转数组
     * 
     * @param obj
     * @return
     */
    public static byte[] serialize(Object object) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            oos.flush();
            bytes = CompressUtil.compress(bos.toByteArray());// 在这里对byte压缩
            oos.close();
            bos.close();
        } catch (IOException ex) {
            Assert.RuntimeException("Object转byte[]出现错误");
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 数组转对象
     * 
     * @param bytes
     * @return
     */
    public static Object deserialize(byte[] bytes) {
        Object object = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(CompressUtil.uncompress(bytes));// 在这里解压
            ObjectInputStream ois = new ObjectInputStream(bis);
            object = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            Assert.RuntimeException("byte[]转对象错误");
            ex.printStackTrace();
        }
        return object;
    }

}

猜你喜欢

转载自www.cnblogs.com/light-zhang/p/10895822.html