序列化就是把程序中的的非静态的成员变量存储到文件中,反序列化就是把序列化文件变成程序。注意序列化和反序列化的过程中,类一定要相同。
创建类:
package com.sxt;
import java.io.Serializable;
public class Student implements Serializable{ //实现接口,此接口中没有任何方法,只是标识接口
/**
*
*/
private static final long serialVersionUID = 1L; //判断jdk版本是否一致,一致才可以反序列化
//transient 的关键字修饰不被序列化
private transient String name;
private Integer age;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
序列化和反序列化
package com.sxt;
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 ObjectStreamDemo {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
Student s=new Student();
s.setAge(23);
s.setName("杨狗");
//序列化
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("E:/a.txt")));
oos.writeObject(s);
//反序列化
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File("E:/a.txt")));
Student r = (Student)ois.readObject();
System.out.println(r.getName()+""+r.getAge());
ois.close();
}
}