import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
public Student(){
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//对象序列化
import java.io.*;
//对象序列化,使用ObjectOutputStream把内存中对象存入到磁盘文件中。
public class ObjectOutputStreamDemo {
public static void main(String[] args) throws Exception {
//创建学生对象
Student s =new Student(“abc”,4);
ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream("D:\\JAVA1\\src\\data2.txt"));
oos.writeObject(s);
oos.close();
System.out.println("序列化完成");
}
}
对象反序列化
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.ObjectInputStream;
public class ObjectInputStreamDemo {
public static void main(String[] args) throws Exception {
ObjectInputStream ois =new ObjectInputStream(new FileInputStream(“D:\JAVA1\src\data2.txt”));
Student s = (Student) ois.readObject();
System.out.println(s);
ois.close();
}
}
注意:
transient 修饰的成员变量不参与序列化
例:private transient int age;
序列化的版本号与反序列化的版本号必须一致才不会出错
private static final long serialVersionUID =1;