序列化/反序列化,我忍你很久了!
案例:序列化学生集合信息,并反序列化。 public class StudentTest { public static void main(String[] args) { String path = "student.dat"; addStudent(path); inputStreamStudent(path); } // 反序列化,并循环输出 private static void inputStreamStudent(String path) { try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(path)); List<Student> stus = (List<Student>) inputStream.readObject(); System.out.println("反序列化结果为:"); stus.forEach(student -> { student.show(); }); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private static void addStudent(String path) { String i = null; List<Student> list = new ArrayList<>(); Student stu = null; do { stu = new Student(); Scanner sc = new Scanner(System.in); System.out.print("请录入学生学号:"); stu.setId(sc.nextInt()); System.out.print("请录入学生姓名:"); stu.setName(sc.next()); System.out.print("请录入学生性别:"); stu.setGender(sc.nextInt()); list.add(stu); System.out.print("是否继续添加(y/n):"); i = sc.next(); } while ("y".equals(i)); System.out.println(list.size()); // 序列化保存学生的集合对象 try { ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(path)); outputStream.writeObject(list); System.out.println("success=============="); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } } public class Student implements Serializable { private static final long serialVersionUID = -3510737277769843023L; private Integer id; private String name; private Integer gender; // 0代表男;1代表女 public void show(){ String s = null; s = (this.gender == 0)?"男":"女"; System.out.println("Student{" + "id=" + id + ", name='" + name + '\'' + ", gender=" + s + '}'); } }