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();
本文链接:https://my.lmcjl.com/post/18857.html
展开阅读全文
4 评论