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;
}
}