Java学习-IO流-序列化流综合练习

Java学习-IO流-序列化流综合练习

public class Student implements Serializable{private String name;private int age;private String address;@Seriaprivate static final long serialVersionUID = 123456789L;
}

序列化:

Student s1 = new Student("高启强",23,"南京");
Student s2 = new Student("安欣",24,"重庆");
Student s3 = new Student("泰叔",25,"上海");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("..\\xx.txt"));
oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(s3);
oos.close();

反序列化:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("..\\xx.txt"));
Student s1 = ois.readObject();
Student s2 = ois.readObject();
Student s3 = ois.readObject();
sout(s1);//→ Student{name=高启强,age=23,address=南京}
sout(s2);//→ Student{name=安欣,age=24,address=重庆}
sout(s3);//→ Student{name=泰叔,age=25,address=上海}
ois.close();

拓展:如果文件中只有三个对象却反序列化四次,则会报错:EOFException
解决方案:把对象都放入 List 中

Student s1 = new Student("高启强",23,"南京");
Student s2 = new Student("安欣",24,"重庆");
Student s3 = new Student("泰叔",25,"上海");ArrayList<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("..\\xx.txt"));
oos.writeObject(list);
oos.close();

反序列化:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("..\\xx.txt"));
ArrayList<Student> list = (ArrayList<Student>)ois.readObject();
for(Sutdent student:list){sout(student);
}
//→ Student{name=高启强,age=23,address=南京}
//→ Student{name=安欣,age=24,address=重庆}
//→ Student{name=泰叔,age=25,address=上海}
ois.close();


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部