一、首先创建需要序列化的类
import java.io.Serializable;
/*
* 对象的序列化和反序列化
* 2016/10/7
* 对象的序列化需要实现Serializable
*/
public class Student {
private String name;
private int age;
private transient String stuNum;
/*
* 使用transient关键字让该元素避免被JVM默认序列化,
* 不过可以自己写readObject和writeObject方法实现序列化
*/
public Student(){
System.out.println("我是Student");
}
public Student(String stuNum,String name,int age){
this.stuNum=stuNum;
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;
}
public String getStuNum() {
return stuNum;
}
public void setStuNum(String stuNum) {
this.stuNum = stuNum;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", stuNum=" + stuNum + "]";
}
}
class StuChildren extends Student implements Serializable{
public StuChildren(){
System.out.println("我是stuChildren");
}
}
class StuGrandchildren extends StuChildren{
public StuGrandchildren(){
System.out.println("我是StuGrandchildren");
}
}
二、对对象进行序列化和反序列化操作
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;
/*
* 使用ObjectOutputStream和ObjectInputStream实现对象的序列化和反序列化
*/
public class ObjectSeriaTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
File file=new File("ost.txt");
if(!file.exists())
file.createNewFile();
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
// Student stu=new Student("0063","小茗",18);
// oos.writeObject(stu);
StuChildren sc=new StuChildren();
oos.writeObject(sc);
oos.flush();
oos.close();
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
// Student newStu=(Student) ois.readObject();
// System.out.println(newStu.toString());
StuChildren newSc=(StuChildren) ois.readObject();
/*
* 所有的没有实现序列化接口的父类的构造函数都会被显式调用
* 实现了序列化接口的父类已被写入文件,在反序列化时隐式调用
*/
ois.close();
}
}