有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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();
        }


    }

共 (2) 个答案

  1. # 1 楼答案

    这是因为我认为ObjectOutputStream将返回文件中的第一个对象。 如果您想要所有可用于循环的对象,请按以下方式使用-:

        FileInputStream fis = new FileInputStream("OutObject.txt");
    
        for(int i=0;i<3;i++) {
            ObjectInputStream ois = new ObjectInputStream(fis);
            Employee emp2 = (Employee) ois.readObject();
    
            System.out.println("Name: " + emp2.getName());
            System.out.println("D.O.B.: " + emp2.getSirName());
            System.out.println("Department: " + emp2.getId());
        }
    
  2. # 2 楼答案

    好的,所以每次新学生进来时,你都会存储整个学生名单,所以基本上你的文件保存的是:

    1. 列出一个学生
    2. 列出两名学生,包括第一名
    3. 3名学生名单
    4. 等等等等

    我知道你可能认为它只会以渐进的方式写新生,但你错了

    你应该先把你想储存的所有学生都加到列表中。然后将完整的列表存储到文件中,就像您正在做的那样

    现在,当您阅读该文件时,首先readObject将返回列表1,这就是为什么您只获得一名学生的列表。第二次阅读会给你列出第二条等等

    因此,保存数据时,必须:

    1. 创建包含N个学生的完整列表,并将其存储到文件中
    2. 不要使用列表,而是直接将学生存储到文件中

    回顾一下:

    1. readObject一次,所以你会得到List<Students>
    2. 通过多次调用readObject从文件中逐个阅读学生