序列化 (Serialization)将对象的状态信息转换为可以存储或传输的形式的过程;对于一个对象来说,对象的状态信息是可变的,比如说,tony作为一个对象,他可能今天在上课,明天在游玩,这就是两个状态,如果我们将他的状态信息写下来,可以寄给别人,这就是序列化。在序列化期间,对象将其当前状态写入到临时或持久性存储区。以后,可以通过从存储区中读取或反序列化对象的状态,重新创建该对象。
序列化的目的1、以某种存储形式使自定义对象持久化;
2、将对象从一个地方传递到另一个地方,例如A服务器中的对象传递到B服务器中。
3、使程序更具维护性
注意:序列化的前提是被序列化的类必须实现java.io.Serializable接口,该接口是一个空接口,即接口内没有定义任何属性和方法。
class Student implements Serializable {
//定义一个Student类,实现Serialixzable接口
//定义student的姓名年龄
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + ", " + age;
}
}
public class ObjectStreamDemo {
public static void main(String[] args) {
//创建两个对象
Student s1 = new Student("晁盖", 25);
Student s2 = new Student("朱仝", 23);
try {
//使用FileOutPutStream打开文件
//开始实例化
FileOutputStream fos = new FileOutputStream("C:/1.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//写入对象信息
oos.writeObject(s1);
oos.writeObject(s2);
//关闭文件
oos.close();
//读文件
FileInputStream fis = new FileInputStream("C:/1.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Student t1 = (Student) ois.readObject();
Student t2 = (Student) ois.readObject();
ois.close();
System.out.println(t1);
System.out.println(t2);
} catch (Exception e) {
System.out.println("操作错误!");
}
}
}



