JAVA单排日记-2020/1/29-序列化练习_序列化集合

在这里插入图片描述
写入

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;

public class Demo05 {
    public static void main(String[] args) throws IOException {
        Student one = new Student("张三",11);
        Student two = new Student("李四",21);
        Student three = new Student("王五",13);
        Student four = new Student("赵六",61);

        List<Student> list= List.of(one,two,three,four);

        ObjectOutputStream file = new ObjectOutputStream(new FileOutputStream("G:\\Java\\测试文件夹\\Student.txt"));
        
        file.writeObject(list);
        
    }
}

读取

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

public class Demo09 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream file = new ObjectInputStream(new FileInputStream("G:\\Java\\测试文件夹\\Student.txt"));

        List<Student> students = (List<Student>) file.readObject();

        file.close();

        for (int i = 0; i <students.size(); i++) {
            System.out.println(students.get(i));
        }
    }
}

在这里插入图片描述

发布了131 篇原创文章 · 获赞 1 · 访问量 4459

猜你喜欢

转载自blog.csdn.net/wangzilong1995/article/details/104108697
今日推荐