/**
* 将对象转换为字节数组(序列化)
* @param
* @param obj
* @return
* @throws IOException
*/
public static byte[] getObjectByteArray(T obj) throws IOException{
ByteArrayOutputStream bo = null;
ObjectOutputStream oo = null;
byte[] array = null;
try {
bo = new ByteArrayOutputStream();
oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
array = bo.toByteArray();
} catch (IOException e) {
throw e;
}finally{
if(oo != null){
oo.close();
}
if(bo != null){
bo.close();
}
}
return array;
}
/**
* 将字节数组转换为对象(反序列化)
* @param bytes
* @return
* @throws Exception
*/
public static Object byteToObject(byte[] bytes) throws Exception {
Object obj = null;
ByteArrayInputStream bi = null;
ObjectInputStream oi = null;
try {
// bytearray to object
bi = new ByteArrayInputStream(bytes);
oi = new ObjectInputStream(bi);
obj = oi.readObject();
} catch (Exception e) {
throw e;
}finally{
if(null != oi){
oi.close();
}
if(null != bi){
bi.close();
}
}
return obj;
}
Java对象的序列化与反序列化
最新推荐文章于 2024-08-09 20:08:07 发布