com.feingto.cloud.kit.SerializeKit Maven / Gradle / Ivy
package com.feingto.cloud.kit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* 对象的Java序列化与反序列化
*
* @author longfei
*/
public class SerializeKit {
/**
* 对象的序列化,把Java对象转换为字节序列。
*
* @param obj Java对象
* @return byte[]
*/
public static byte[] serialize(Object obj) {
byte[] bytes = new byte[1024];
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
/**
* 对象的反序列化,把字节序列恢复为Java对象。
*
* @param bytes 字节数组
* @return Object
*/
public static Object unserialize(byte[] bytes) {
Object obj = new Object();
try {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
obj = oi.readObject();
bi.close();
oi.close();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}