一、什么是序列化和反序列化
序列化:将对象状态信息转化成可以存储或传输的形式的过程(Java中就是将对象转化成字节序列的过程)
反序列化:从存储文件中恢复对象的过程(Java中就是通过字节序列转化成对象的过程)
二、为什么要使用序列化
Java中对象都是存储在内存中,准确地说是JVM的堆或栈内存中,可以各个线程之间进行对象传输,但是无法在进程之间进行传输。另外如果需要在网络传输中传输对象也没有办法,同样内存中的对象也没有办法直接保存成文件。所以需要对对象进行序列化,序列化对象之后一个个的Java对象就变成了字节序列,而字节序列是可以传输和存储的。而反序列化就可以通过序列化生产的字节序列再恢复成序列化之前的对象状态及信息。
总结:
1、进程之间传输对象(如RPC、RMI通信)
2、网络通信时进行传输对象
3、持久化对象时需要将对象序列化
三、测试用例
将对象序列化到本地文件中,然后再还原。
public class JdkSerialization {
public static void main(String[] args) throws Exception {
serialize("测试序列化");
String s = deserialize();
System.out.println("s="+s);
}
public static void serialize(Object object) throws Exception {
File file = new File("C:\\Users\\Administrator\\Desktop\\1.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(fileOutputStream);
os.writeObject(object);
os.flush();
os.close();
fileOutputStream.close();
}
public static String deserialize() throws Exception {
FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\1.txt"));
ObjectInputStream in = new ObjectInputStream(fileInputStream);
Object o = in.readObject();
System.out.println(o);
return (String)o;
}
}
四、序列化成可传输内容
public interface Serialization {
/**
* 序列化
*/
<T> byte[] serialize(T obj);
/**
* 反序列化
*/
<T> T deserialize(byte[] data, Class<T> cls);
}
public class JdkSerialization implements Serialization{
@Override
public <T> byte[] serialize(T obj) {
if (obj == null){
throw new RuntimeException("serialize object is null");
}
try{
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(os);
out.writeObject(obj);
return os.toByteArray();
}catch (IOException e){
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public <T> T deserialize(byte[] data, Class<T> cls) {
if (data == null){
throw new RuntimeException("deserialize data is null");
}
try{
ByteArrayInputStream is = new ByteArrayInputStream(data);
ObjectInputStream in = new ObjectInputStream(is);
return (T) in.readObject();
}catch (Exception e){
throw new RuntimeException(e.getMessage(), e);
}
}
public static void main(String[] args) {
Serialization jdkSerialization = new JdkSerialization();
byte[] datas = jdkSerialization.serialize("大家好");
String deserialize = jdkSerialization.deserialize(datas, String.class);
System.out.println("deserialize="+deserialize);
}
}