对象序列化需继承Serializable类
import java.io.Serializable;
public class LogObj implements Serializable {}
/**
* 序列化
* @param object
* @return byte[]
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
bytes = baos.toByteArray();
} catch (Exception e) {
System.out.println("对象序列化错误!");
}
return bytes;
}
/**
* 反序列化
* @param bytes
* @return Object
*/
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
Object object = null;
try {
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
object = ois.readObject();
} catch (Exception e) {
System.out.println("对象反序列化错误!");
}
return object;
}