java对象和byte数组互转,直接拿去用

//加了了Optional防止空指针异常,加入了泛型,省去了强制转化
import java.io.*;
import java.util.Optional;

/**
 * Created by Jason on 2017/1/3.
 */
public class ByteArrayUtils {

    public static<T> Optional<byte[]> objectToBytes(T obj){
        byte[] bytes = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream sOut;
        try {
            sOut = new ObjectOutputStream(out);
            sOut.writeObject(obj);
            sOut.flush();
            bytes= out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Optional.ofNullable(bytes);
    }

    public static<T> Optional<T> bytesToObject(byte[] bytes) {
        T t = null;
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ObjectInputStream sIn;
        try {
            sIn = new ObjectInputStream(in);
            t = (T)sIn.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Optional.ofNullable(t);

    }
}
阅读更多
个人分类: Java
上一篇java的Arrays工具类
下一篇effective java 1
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭