/*
*序列化时,非静态的对象或者变量会存入对象图,单静态的不会
*如果想要非静态的变量或者对象存入对象图,则可以将其声明为瞬时变量(transient)
*/
public class SerializableDemo {@Test
public void t1() throws IOException, IOException{//写
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("p.txt"));
Person p1=new Person("1", "Rose", 20);
Person p2=new Person("2", "Jack", 22);
System.out.println(p1.getNum());
out.writeObject(p1);
out.writeObject(p2);
out.close();
}
@Test
public void t2() throws IOException, IOException{//读
ObjectInputStream in=new ObjectInputStream(new FileInputStream("p.txt"));
while(true){
try {
Person p=(Person) in.readObject();
System.out.println(p);
} catch (EOFException e) {//EOFException判断数据是否读取完毕
System.out.println("数据读取完毕");
break;
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
in.close();
}
}
public class Person implements Serializable{//被序列化的对象必须实现Serializable接口
private String uuid;private String name;
private int age;
private static int num;
public Person(){
this("","",0);
}
public Person(String uuid,String name,int age){
this.uuid=uuid;
this.name=name;
this.age=age;
num++;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
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;
}
@Override
public String toString() {
return uuid + ", " + name + ", " + age +","+num;
}
public static int getNum() {
return num;
}
public static void setNum(int num) {
Person.num = num;
}
}