概念介绍
把Java对象转换为字节序列的过程称为对象的序列化。
把字节序列恢复为Java对象的过程称为对象的反序列化。
对象的序列化主要有两种用途:
1) 数据介质存储
2) 数据网络传输
1)对象序列化–java
public byte[] serialize(Object obj) throws Exception {
if(obj==null) throw new NullPointerException();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(os);
out.writeObject(obj);
return os.toByteArray();
}
public Object deserialize(byte[] by) throws Exception {
if(by==null) throw new NullPointerException();
ByteArrayInputStream is = new ByteArrayInputStream(by);
ObjectInputStream in = new ObjectInputStream(is);
return in.readObject();
}
2)对象序列化–hessian
public byte[] serialize(Object obj) throws IOException{
if(obj==null) throw new NullPointerException();
ByteArrayOutputStream os = new ByteArrayOutputStream();
HessianOutput ho = new HessianOutput(os);
ho.writeObject(obj);
return os.toByteArray();
}
public Object deserialize(byte[] by) throws IOException{
if(by==null) throw new NullPointerException();
ByteArrayInputStream is = new ByteArrayInputStream(by);
HessianInput hi = new HessianInput(is);
return hi.readObject();
}
3)对象序列化–kryo
/**
* Kryo serialize
*
* @param source
* @return
* @throws IOException
*/
public static byte[] KryoSerialize(Object source) throws IOException {
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
Kryo kryo = new Kryo();
Output output = new Output(bos);
kryo.writeObject(output, source);
output.flush();
output.close();
return bos.toByteArray();
} finally {
try {
bos.close();
} catch (IOException e) {
log.warn("IOException while kryoWriteObject final:", e);
}
}
}
/**
* Kryo deserialize
*
* @param bytes,Class
* @return
* @throws IOException
*/
public static <T> T KryoDeserialize(byte[] bytes, Class<T> type) throws IOException {
if (bytes == null) {
return null;
}
Kryo kryo = new Kryo();
Input input = new Input(bytes);
T obj = kryo.readObject(input, type);
input.close();
return obj;
}
public static void main(String[] args) throws IOException {
System.out.println("start");
byte[] ser = KryoSerialize(1L);
System.out.println("KryoSerialize=====" + new String(ser));
System.out.println("KryoDeserialize=====" + KryoDeserialize(ser, Long.class));
}