簡體   English   中英

ObjectOutputStream, readObject 只從序列化文件中讀取第一個對象

[英]ObjectOutputStream, readObject only reads first object from serialized file

我有一個對象的 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. 與一名學生一起列出
  2. 列出包括第一個在內的兩個學生
  3. 3名學生名單
  4. 等等等等。

我知道您可能認為它只會以增量方式編寫新學生,但您在這里錯了。

您應該先將要存儲的所有學生添加到列表中。 然后將完整列表存儲到文件中,就像您正在做的那樣。

現在,當您從 filre 中閱讀時,第一個readObject將返回第 1 個列表 - 這就是為什么您只獲得一個學生的列表。 第二次閱讀會給你列表 2 等。

所以你保存你的數據你要么必須:

  1. 創建包含 N 個學生的完整列表並將其存儲到文件中
  2. 不要使用列表,而是將學生直接存儲到文件中

讀回來:

  1. readObject一次,所以你會得到List<Students>
  2. 通過多次調用readObject從文件中一一讀取學生

這是因為我認為 ObjectOutputStream 會從文件中返回第一個對象。 如果你想要所有的對象,你可以使用 for 循環並像這樣使用 -:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM