java之数组和对象的互转
java
* 对象转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;
}
}