java ObjectOutputStream,readObject仅从序列化文件读取第一个对象
我有一个对象的ArrayList,我想将它们存储到文件中,并且我想将它们从文件读取到ArrayList。我可以使用writeObject方法成功地将它们写入文件,但当从文件读取到ArrayList时,我只能读取第一个对象。下面是我从序列化文件读取的代码
public void loadFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
myStudentList = (ArrayList<Student>) ois.readObject();
}
编辑:
这是将列表写入文件的代码
public void saveToFile(ArrayList<Student> list) throws IOException {
ObjectOutputStream out = null;
if (!file.exists ()) out = new ObjectOutputStream (new FileOutputStream (file));
else out = new AppendableObjectOutputStream (new FileOutputStream (file, true));
out.writeObject(list);
}
我班的其他同学
public class Student implements Serializable {
String name;
String surname;
int ID;
public ArrayList<Student> myStudentList = new ArrayList<Student>();
File file = new File("src/files/students.txt");
public Student(String namex, String surnamex, int IDx) {
this.name = namex;
this.surname = surnamex;
this.ID = IDx;
}
public Student(){}
//Getters and Setters
public void add() {
Scanner input = new Scanner(System.in);
System.out.println("name");
String name = input.nextLine();
System.out.println("surname");
String surname = input.nextLine();
System.out.println("ID");
int ID = input.nextInt();
Ogrenci studenttemp = new Ogrenci(name, surname, ID);
myOgrenciList.add(studenttemp);
try {
saveToFile(myOgrenciList, true);
}
catch (IOException e){
e.printStackTrace();
}
}
# 1 楼答案
这是因为我认为ObjectOutputStream将返回文件中的第一个对象。 如果您想要所有可用于循环的对象,请按以下方式使用-:
# 2 楼答案
好的,所以每次新学生进来时,你都会存储整个学生名单,所以基本上你的文件保存的是:
我知道你可能认为它只会以渐进的方式写新生,但你错了
你应该先把你想储存的所有学生都加到列表中。然后将完整的列表存储到文件中,就像您正在做的那样
现在,当您阅读该文件时,首先
readObject
将返回列表1,这就是为什么您只获得一名学生的列表。第二次阅读会给你列出第二条等等因此,保存数据时,必须:
回顾一下:
readObject
一次,所以你会得到List<Students>
readObject
从文件中逐个阅读学生