利用ObjectInputStream、ObjectOutputStream序列化多个对象

来源:互联网 发布:讨鬼传极优化 编辑:程序博客网 时间:2024/05/22 10:34

内容:序列化多个对象,利用一个容器存储你要序列化的多个对象。


class Student implements java.io.Serializable{private String name;public Student(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}}public class Serializable {public static final File file = new File(System.getProperty("user.dir") + File.separator + "data" + File.separator + "student.txt");public static void doWrite(List<Student> list) throws FileNotFoundException, IOException {if (file.exists() == false)file.createNewFile();ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(file, true));output.writeObject(list);output.flush();output.close();}public static void doRead() throws FileNotFoundException, IOException, ClassNotFoundException {ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));List<Student> list = (List<Student>) input.readObject();System.out.println(list.size());for (Student i : list)System.out.println(i.getName());input.close();}public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {List<Student> list = new ArrayList<Student>();list.add(new Student("asds"));list.add(new Student("base"));doWrite(list);doRead();}}


1 0
原创粉丝点击