import java.io.Serializable;
public class Main{
/*
* Serialiazable:用于给被序列化的类加ID号
* 用于判断类和对象是否是同一个版本
* 默认的ID号是根据类中各个属性签名算出的。自定义序列号后即使改动权限关键字也可以反序列化。
*
*
* transient:将被修饰的东西变为瞬时的,序列化时不会被序列化
* 静态(方法区)和瞬态字段不会被ObjectOutputStream中的writeObject()写入
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException {
//ObjectInputStream与ObjectOutputStream均需实现Serializable接口
//该技术是把对象写入硬盘中(把对象持久化)
writeObj();
readObj();
}
public static void readObj() throws FileNotFoundException, IOException, ClassNotFoundException {
//ObjectInputStream只能读ObjectOutputStream写入的对象,一次读一个
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\obj.object"));
Person p = (Person)ois.readObject(); //读取对象需要.object和类文件两个文件侧可以读取。
System.out.println(p.getAge());
}
public static void writeObj() throws FileNotFoundException, IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\obj.object"));
oos.writeObject(new Person("mike",11));
}
}
class Person implements Serializable{
private String name;
private int age;
Person(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;
}
}