对象的持久化(序列化、可串行性)存储:把对象长久的保存到介质(如硬盘)上
Serializable:标记接口
静态成员不能被序列化
被transient关键字修饰的属性不能被序列化
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = -5860362650214690232L;
private String name;
private transient int age;
public 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;
}
}
import java.io.*;
public class ObjectStreamDemo {
public static void main(String[] args) throws Exception {
// writeObj();
readObj();
}
public static void writeObj() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("E:\\obj.txt"));
oos.writeObject(new Person("zhangsan", 12));
oos.close();
}
public static void readObj() throws Exception {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("E:\\obj.txt"));
Object obj = ois.readObject();
Person p = (Person) obj;
System.out.println(p.getName() + ": " + p.getAge());
ois.close();
}
}
网友评论