序列化就是将一个实例化的对象的状态信息转换为可保持或传输的格式的过程(即只操作对象的属性值而不操作方法)。将一个实例化对象进行序列化操作,将其变成一个字符串流,从而可以使其可以通过socket进行传输、或者持久化到存储数据库或文件系统中;然后在需要的时候通过字节流中的信息来重构一个相同的对象。
序列化的实现:
将需要被序列化的类实现Serializable接口,该接口没有需要实现的方法,implements Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态);同样,使用ObjectInputStream对象的readObject()就可以将obj读出。
实例:
a.首先定义一个将被序列化的Student类
package com.neusoft.test1;
import java.io.Serializable;
class Student implements Serializable {// 定义一个可以被序列化的类
String name;
int age;
String num;
double score;
public Student() {
}
public Student(String name, int age, String num, double score) {
this.name = name;
this.age = age;
this.num = num;
this.score = score;
}
public String toString() {
return name + "\t" + age + "\t" + num + "\t" + score;
}
}
b.定义一个用于将Student对象序列化的类
package com.neusoft.test1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializableTest {
public static void main(String[] args) {
Student stu_1 = new Student("wjl", 25, "47843847", 89);// 实例化两个可以被序列化的student对象
Student stu_2 = new Student("yxm", 23, "47856547", 99);
File f = new File("c:/demo/456.txt");// 保存两个对象的文件对象
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("没有被序列化时的对象如下:");
System.out.println(stu_1);
System.out.println(stu_2);
oos.writeObject(stu_1);
oos.writeObject(stu_2);
System.out.println("序列化成功!!");
oos.flush();
fos.close();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
c.定义一个用于将Student对象反序列化的类
package com.neusoft.test1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class TurnSerializableTest {
public static void main(String[] args) {
File f = new File("c:/demo/456.txt");
try {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Student stu_1;
stu_1 = (Student) ois.readObject();
System.out.println(stu_1);
Student stu_2 = (Student) ois.readObject();
System.out.println(stu_2);
fis.close();
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
d.将这三个类放在一个包下,首先执行SerializableTest类将Student的两个对象序列化,并保存到c:/demo/456.txt文件中,然后再执行TurnSerializableTest类将c:/demo/456.txt文件中保存的两个Student对象反序列化回来