写入
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));
}
}
}