序列化就是一种用来处理对象流的机制,所谓的对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可以将流化后的对象那个传输与网络之间。序列化是为了解决在对对象流进行读写操作时所引发的问题。
序列化的实现:将需要被序列化的类实现Serialization接口,该接口没有需要实现的方法,implements serialization只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj对象写出(既保存期状态),要恢复的话则用输入流。
代码实现:
对象:
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
private transient boolean sex;
public Student(String name, int age, boolean sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
实现对象流
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Test6 {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
test1();
test2();
}
public static void test1() throws FileNotFoundException, IOException {
Student student = new Student("qy", 21, false);
// 序列化
String name1 = "d:" + File.separator + "a/e.txt";
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(name1));
out.writeObject(student);
out.close();
System.out.println("over!");
}
public static void test2() throws FileNotFoundException, IOException, ClassNotFoundException {
String name1 = "d:" + File.separator + "a/e.txt";
// 反序列化
ObjectInputStream in = new ObjectInputStream(new FileInputStream(name1));
Student student = (Student) in.readObject();
in.close();
System.out.println(student);
}
}