流的序列化
-
序列化又称串行化:将实现了
seriallizable
接口的对象转换为一个字节序列,并能够在以后将这个字节序列完全恢复为原来的对象,后者成为反序列化 -
序列化的目的:便于介质存储和网络传输
-
使用的类:
ObjectInputStream
和ObjectOutputStream
实例
先将s1对象序列化,最后在反序列化还原,得到的是同样的内容
import java.io.*;
public class Student implements Serializable { //序列化
int number=1;
String name;
Student(int number,String n1) {
this.number = number;
this.name = n1;
}
void save(String fname) {
try {
FileOutputStream fout = new FileOutputStream(fname);
//得到ObjectOutputStream对象
ObjectOutputStream out = new ObjectOutputStream(fout);
//对象序列化
out.writeObject(this);
out.close();
}
catch (FileNotFoundException fe){}
catch (IOException ioe){}
}
void display(String fname) {
try{
FileInputStream fin = new FileInputStream(fname);
//得到ObjectInputStreamd
ObjectInputStream in = new ObjectInputStream(fin);
//对象反序列化
Student u1 = (Student)in.readObject();
System.out.println(u1.getClass().getName()+" "+u1.getClass().getInterfaces()[0]);
System.out.println(" "+u1.number+" "+u1.name);
in.close();
}
catch (FileNotFoundException fe){}
catch (IOException ioe){}
catch (ClassNotFoundException ioe) {}
}
public static void main(String arg[]) {
String fname = "Student.obj"; //文件名
Student s1 = new Student(1,"Wang");
//先将s1对象序列化
s1.save(fname);
//反序列化并打印出
s1.display(fname);
}
}