Java 序列化
序列化(对象写入文件) 反序列化(从文件读取对象)
public class Demo01 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//序列化 对象写入文件
FileOutputStream fos=new FileOutputStream("D:\\person.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);//序列化
Person p=new Person("zhangsan",18); //对象 需要实现接口
oos.writeObject(p); //写入对象 对象可为 存储Person的集合
oos.close();
//反序列化 从文件中读出对象
FileInputStream fis=new FileInputStream("D:\\person.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
try {
while(true) { //Person.class丢失ClassNotFoundException
Object obj = ois.readObject(); //读取对象
Person p2=(Person)obj; //转Person类型
System.out.println(p2); //输出 调用p2.toString()
}
} catch(EOFException e) {
System.out.println("读到了文件的末尾");
}
ois.close();
}
}
public class Person implements Serializable{//实现(标记类)接口 无抽象方法
private String name; //对象才可以序列化
//private int age;
//private static int age;//静态修饰 是类的数据 也不会被序列化
private transient int age;//瞬态关键字transient修饰的属性不会序列化
private static final long serialVersionUID=4321L;//序列化号写死
//修改Person类后也能反序列化
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 Person(){super();}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}