首页 > 解决方案 > ArrayList 上的可序列化丢失一些数据

问题描述

我有一个 Employee 对象的 ArrayList,其中 Employee 类实现了 Serializable。我正在使用此代码将列表写入文件:

ArrayList<Employee> empList = new ArrayList<>();
  FileOutputStream fos = new FileOutputStream("EmpObject.ser");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  // write object to file
  empList .add(emp1);
  empList .add(emp2);
  oos.writeObject(empList);

  empList .add(emp3);

  oos.writeObject(empList);
}

如果我尝试反序列化它,我只会得到前两个对象而不是第三个对象。任何人都可以试试这是为什么?

编辑1:如果我一次添加所有元素,一切都很好,但不是我第一次做的方式。有什么区别?

ArrayList<Employee> empList = new ArrayList<>();
  FileOutputStream fos = new FileOutputStream("EmpObject.ser");
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  // write object to file
  empList .add(emp1);
  empList .add(emp2);
  empList .add(emp3);
  oos.writeObject(empList);
}

在此之后我有 3 个元素

标签: javaserializable

解决方案


正如 GhostCat 和 uaraven 已经提到的那样,reset 并不是您期望的那样,您应该查看有关序列化的教程,并可能考虑使用 sth。否则,如果这不适合您的用例。

如果创建一个新的 FileOutputStream,您的代码可能如下所示:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class SerializationTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String path = "EmpObject.ser";

        ArrayList<Employee> empList = new ArrayList<>();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));

        empList.add(emp1);
        empList.add(emp2);
        oos.writeObject(empList);

        empList.add(emp3);
        // Create a new FileOutputStream to override the files content instead of appending the new employee list
        oos = new ObjectOutputStream( new FileOutputStream(path));
        oos.writeObject(empList);

        ObjectInputStream objectinputstream = new ObjectInputStream(new FileInputStream(path));
        List<Employee> readCase = (List<Employee>) objectinputstream.readObject();

        System.out.println(readCase);
    }
}

推荐阅读