6-1 序列化基本操作
1、对象序列化,就是将Object转换成byte序列,反之叫对象的反序列化
2、序列化流(ObjectOutputStream),是过滤流----writeObject
反序列化流(ObjectInputStream)----readObject
3、序列化接口(Serializable)
对象必须实现序列化接口,才能进行序列化,否则将出现异常
这个接口,没有任何方法,只是一个标准
import java.io.Serializable;
public class Student implements Serializable{
private String stuno;
private String stuname;
private int stuage;
public Student(){
}
public Student(String stuno, String stuname, int stuage) {
super();
this.stuno = stuno;
this.stuname = stuname;
this.stuage = stuage;
}
public String getStuno() {
return stuno;
}
public void setStuno(String stuno) {
this.stuno = stuno;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public int getStuage() {
return stuage;
}
public void setStuage(int stuage) {
this.stuage = stuage;
}
@Override
public String toString() {
return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
+ stuage + "]";
}
}
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 Test {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
String file="demo/obj.dat";
//1.对象的序列化(应用于网络传输)
// ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
// Student stu=new Student("1","alice",12);
// oos.writeObject(stu);
// oos.flush();
// oos.close();
//2.反序列化
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
Student stu=(Student)ois.readObject();
System.out.println(stu);
ois.close();
}
}