流的序列化

 

/*

*序列化时,非静态的对象或者变量会存入对象图,单静态的不会

*如果想要非静态的变量或者对象存入对象图,则可以将其声明为瞬时变量(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;
}
    
     
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值