importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.Closeable;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.util.ArrayList;importjava.util.List;/*** 序列化,反序列化工具
*
* @project iweixin-pay
* @fileName SerializeUtil.java
* @Description
*@authorlight-zhang
* @date 2018年5月31日上午9:51:25
*@version1.0.0*/
public classSerializeUtil {public static byte[] serialize(Object object) {
ObjectOutputStream oos= null;
ByteArrayOutputStream baos= null;try{//序列化
baos = newByteArrayOutputStream();
oos= newObjectOutputStream(baos);
oos.writeObject(object);byte[] bytes =baos.toByteArray();returnbytes;
}catch(Exception e) {
e.printStackTrace();
}finally{
close(oos);
close(baos);
}return null;
}public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais= null;
ObjectInputStream ois= null;try{//反序列化
bais = newByteArrayInputStream(bytes);
ois= newObjectInputStream(bais);returnois.readObject();
}catch(Exception e) {
e.printStackTrace();
}finally{
close(bais);
close(ois);
}return null;
}/*** 序列化 list 集合
*
*@paramlist
*@return
*/
public static byte[] serializeList(List>list) {if (list == null || list.size() <= 0) {return null;
}
ObjectOutputStream oos= null;
ByteArrayOutputStream baos= null;byte[] bytes = null;try{
baos= newByteArrayOutputStream();
oos= newObjectOutputStream(baos);for(Object obj : list) {
oos.writeObject(obj);
}
bytes=baos.toByteArray();
}catch(Exception e) {
e.printStackTrace();
}finally{
close(oos);
close(baos);
}returnbytes;
}/*** 反序列化 list 集合
*
*@paramlb
*@return
*/
public static List> unserializeList(byte[] bytes) {if (bytes == null) {return null;
}
List list = new ArrayList();
ByteArrayInputStream bais= null;
ObjectInputStream ois= null;try{//反序列化
bais = newByteArrayInputStream(bytes);
ois= newObjectInputStream(bais);while (bais.available() > 0) {
Object obj=(Object) ois.readObject();if (obj == null) {break;
}
list.add(obj);
}
}catch(Exception e) {
e.printStackTrace();
}finally{
close(bais);
close(ois);
}returnlist;
}/*** 关闭io流对象
*
*@paramcloseable*/
public static voidclose(Closeable closeable) {if (closeable != null) {try{
closeable.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}