package com.yyq;
import java.io.*;
//Serializable 接口没有 ((标记接口 )
// 对象的序列化: 都有一个ID标识: 通常是被编译器识别的
// 对象被序列化,我们无需看的懂,这样的话对象就存起来了
// 可以提供对象和对象的值: 已经封装好了值,不需要自己在创建了
// 类不能被修改 ,当类被修改后会产生无效的类异常
// 可以自定义序列号 (序列号UID 本身是自动生成的)
// UID 给类加一个固定标记
// 序列号: 是根据成员计算得出的
// 静态不能被序列化 transient 可以保护变量不被序列化
class People implements Serializable{
public static final long serialVersionUID = 42L;
String name;
transient int age;
People(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return name+":"+age;
}
}
public class ObjectStreamDemo {
public static void main(String[] args) throws IOException, Exception {
// TODO Auto-generated method stub
// 对象的持久化存储
//writeObj();
//writeObj();
readObj();
}
public static void readObj() throws IOException, Exception{
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("obj.txt"));
People p = (People) ois.readObject();
System.out.println(p);
// 关闭资源
ois.close();
}
public static void writeObj() throws IOException, Exception{
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new People("lsi",35));
oos.close();
}
}