目录
一、序列化相关概念
序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。
整个过程都是 Java 虚拟机(JVM)独立的,也就是说,在一个平台上序列化的对象可以在另一个完全不同的平台上反序列化该对象。
序列化的用途
- 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;
- 在网络上传送对象的字节序列。
序列化的实现
-
java.io.ObjectOutputStream代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写到一个目标输出流中。只有实现了Serializable和Externalizable接口的类的对象才能被序列化。
-
java.io.ObjectInputStream代表对象输入流,它的readObject()方法从一个源输入流中读取字节序列,再把它们反序列化为一个对象,并将其返回。
二、序列化 & 反序列化
首先,我们先定义一个Student1对象类,之后再进行序列化和反序列化,相关代码如下:
import java.io.*;
class Student1 implements Serializable{
public String name;
public String sex;
public int age;
public float height;
public float weight;
public void Information() {
System.out.println("name: " + name
+ ", sex: " + sex
+ ", age: " + age
+ ", height: " + height
+ ", weight: " + weight
);
}
}
public class Day37 {
public static void main(String[] args) throws Exception, IOException{
toSerialize();
toDeserialize();
}
private static void toSerialize() throws FileNotFoundException, IOException {
Student1 stu = new Student1();
stu.name = "Jack";
stu.sex = "man";
stu.age = 18;
stu.height = 188.0F;
stu.weight = 80.0F;
try {
// 序列化到文件中
FileOutputStream fileOut = new FileOutputStream("E:\\Java_project\\src\\Java_learning\\Student1.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(stu);
out.close();
fileOut.close();
System.out.println("序列化成功!");
} catch (IOException i) {
i.printStackTrace();
}
}
private static void toDeserialize() throws FileNotFoundException, IOException{
Student1 stu2 = null;
try{
FileInputStream filein = new FileInputStream("E:\\Java_project\\src\\Java_learning\\Student1.ser");
ObjectInputStream in = new ObjectInputStream(filein);
stu2 = (Student1)in.readObject();
in.close();
filein.close();
System.out.println("反序列化成功!");
}catch (IOException | ClassNotFoundException i){
i.printStackTrace();
}
stu2.Information();
}
}
序列化成功!
反序列化成功!
name: Jack, sex: man, age: 18, height: 188.0, weight: 80.0