java - 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 个元素
解决方案
正如 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);
}
}
推荐阅读
- java - 使用 Rest Assured 的 HTTP POST 请求(示例)
- excel - 通过 Excel VBA 和 ADODB 连接将 Access 查询拉入 Excel
- c++ - 如何正确链接子目录中的静态库?
- python - vscode python调试器不对断点或stoponentry做出反应
- c++ - “标识符未定义”,试图从私有结构创建一个函数
- django - Django 将图像从 URL 保存到模型导致 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
- if-statement - SAS 错误:SUM 的空参数无效
- python - 使用 Python 通过目录中的多个 .csv 文件循环函数
- jupyter-notebook - 谷歌colab中的数据集丢失了?
- python - 使用前一个日期从现有列创建新的 Pandas 列