持久化
【小城贝尔】
今将对象持久化,千百年后在开挂。
接口必先来实现,忽略成员瞬时前。
public class SerializableDemo {
public static void main(String[] args) {
Studen stu = new Studen();
try(ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream("src/obj.oo"));
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(new FileInputStream("src/obj.oo")))){
//将对象写出到文件
obj.writeObject(stu);
obj.flush();
//将文件中的对象读取到内存中
Object object = oin.readObject();
if(object instanceof Studen) {
Studen stud = (Studen)object;
//stud : Studen [name=马克思, age=60, school=北大]
System.out.println("stud : "+stud);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
class Studen implements Serializable{
private String name = "马克思";
private int age = 60;
private String school = "北大";
//加上transient 序列化的时候自动忽略
private transient Date birth = new Date();
public void introduce() {
System.out.println("name : "+ this.name +" age : "+ this.age +" school : " + this.school+" birth : "+this.birth );
}
@Override
public String toString() {
return "Studen [name=" + name + ", age=" + age + ", school=" + school + "]";
}
}