package com.cn.day01.demo.demo3;
import java.io.Serializable;
public class Student implements Serializable {
private static int id_s = 0;
private int id;
private String name;
private int age;
private String collage;
private String location;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", collage='" + collage + '\'' +
", location='" + location + '\'' +
'}';
}
public Student() {
id_s++;
this.id = id_s;
}
public Student(String name, int age, String collage, String location) {
this.id = ++id_s;
this.name = name;
this.age = age;
this.collage = collage;
this.location = location;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCollage() {
return collage;
}
public void setCollage(String collage) {
this.collage = collage;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
package com.cn.day01.demo.demo3;
import java.io.*;
import java.util.ArrayList;
public class IODemo01 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s1 = new Student("李四",19,"PKU","Beijing");
Student s2 = new Student("张三",20,"PKU","Beijing");
Student s3 = new Student("王五",21,"PKU","Beijing");
ArrayList<Student> students = new ArrayList<>();
students.add(s1);
students.add(s2);
students.add(s3);
File file = new File("F:\\Test\\temp\\first\\IdeaProject\\File\\object.txt");
IODemo01 ioDemo01 = new IODemo01();
ioDemo01.objectToFile(students,file);
ArrayList<Student> students_1 = ioDemo01.fileToObject(file);
students_1.add(new Student("merry",18,"PKU","Beijing"));
ioDemo01.objectToFile(students_1,file);
ArrayList<Student> students_2 =ioDemo01.fileToObject(file);
}
public void objectToFile(ArrayList<Student> students,File file) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(students);
oos.flush();
oos.close();
}
public ArrayList<Student> fileToObject(File file) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Student> students = (ArrayList<Student>)ois.readObject();
for (Student student: students) {
System.out.println(student);
}
ois.close();
return students;
}
}