java对象转byte[]数组,byte[] 数组转java对象,demo

demo:

	/**
     * 对象转字节数组
     */
    public static byte[] objectToBytes(Object obj) throws IOException {
        try(
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ObjectOutputStream sOut = new ObjectOutputStream(out);
        ){
            sOut.writeObject(obj);
            sOut.flush();
            byte[] bytes = out.toByteArray();
            return bytes;
        }
    }

    /**
     * 字节数组转对象
     */
    public static Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
        try(
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                ObjectInputStream sIn = new ObjectInputStream(in);
        ){
            return sIn.readObject();
        }
    }

  

end.

posted on 2020-07-11 09:49  梦幻朵颜  阅读(8847)  评论(0编辑  收藏  举报