可在 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);

}

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


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


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个元素


慕莱坞森
浏览 160回答 2
2回答

子衿沉夜

正如GhostCat和uaraven已经提到的,重置并不是你所期望的,你应该看看关于序列化的教程,也许可以考虑使用sth。否则,如果这不适合您的用例。如果创建新的 FileOutputStream,您的代码可能如下所示:import java.io.*;import java.util.ArrayList;import java.util.List;public class SerializationTest {&nbsp; &nbsp; public static void main(String[] args) throws IOException, ClassNotFoundException {&nbsp; &nbsp; &nbsp; &nbsp; String path = "EmpObject.ser";&nbsp; &nbsp; &nbsp; &nbsp; ArrayList<Employee> empList = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));&nbsp; &nbsp; &nbsp; &nbsp; empList.add(emp1);&nbsp; &nbsp; &nbsp; &nbsp; empList.add(emp2);&nbsp; &nbsp; &nbsp; &nbsp; oos.writeObject(empList);&nbsp; &nbsp; &nbsp; &nbsp; empList.add(emp3);&nbsp; &nbsp; &nbsp; &nbsp; // Create a new FileOutputStream to override the files content instead of appending the new employee list&nbsp; &nbsp; &nbsp; &nbsp; oos = new ObjectOutputStream( new FileOutputStream(path));&nbsp; &nbsp; &nbsp; &nbsp; oos.writeObject(empList);&nbsp; &nbsp; &nbsp; &nbsp; ObjectInputStream objectinputstream = new ObjectInputStream(new FileInputStream(path));&nbsp; &nbsp; &nbsp; &nbsp; List<Employee> readCase = (List<Employee>) objectinputstream.readObject();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(readCase);&nbsp; &nbsp; }}

天涯尽头无女友

您的代码会发生什么情况:您将列表写入文件,其中包含两个条目您重置流你再次写列表,有三个条目因此,您的文件包含两个值,是的。两个列表,一个包含 2 个,一个包含 3 个条目。换句话说:不会重置已写入文件的内容!您编写了一个包含两个条目的列表。您只是在重置有关存储对象的信息,以便再次完全序列化&nbsp;emp1 和 emp2。如果没有对重置的调用,JVM 将理解它不需要再次完全序列化 emp1 和 emp2。reset()含义:默认情况下,JVM&nbsp;压缩要传输的数据量。它记住哪些对象已经写入,而不是重复写入它们,它只将类似“之前序列化的对象X再次出现”之类的东西写入流中。所以:我认为你根本不理解方法的意义。解决方案:阅读一个小教程,就像教程点中的一样。reset()根据OP的最新评论进行编辑:你所要求的东西以这种方式是不可能的。您正在编写列表对象。这意味着此时该列表的所有条目都将写入文件。JVM 记住“该列表已经写好了”,所以即使其内部状态在此期间发生了变化,它也不会再写它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java