java - 如何将java序列化对象写入和读取到文件中

标签 java file serialization

我打算将多个对象写入一个文件,然后在我的代码的另一部分中检索它们。我的代码没有错误,但无法正常工作。你能帮我找出我的代码有什么问题吗? 我从不同的网站阅读了不同的代码,但没有一个对我有用!

这是我将对象写入文件的代码: MyClassList 是一个数组列表,其中包含我的类的对象(必须写入文件)。

for (int cnt = 0; cnt < MyClassList.size(); cnt++) {
    FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
    oos.writeObject(MyClassList.get(cnt));
}

我在输出流的构造函数中添加了“true”,因为我想将每个对象添加到文件末尾。对吗?

这是我从文件中读取对象的代码:

 try {
     streamIn = new FileInputStream("G:\\address.ser");
     ObjectInputStream objectinputstream = new ObjectInputStream(streamIn);
     MyClass readCase = (MyClass) objectinputstream.readObject();
     recordList.add(readCase);
     System.out.println(recordList.get(i));
 } catch (Exception e) {
     e.printStackTrace();
 }

它最终只打印出一个对象。现在,我不知道是我写错了还是读错了!

最佳答案

为什么不一次序列化整个列表?

FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);

当然,假设 MyClassList 是一个 ArrayListLinkedList 或另一个 Serializable 集合。

在读回它的情况下,在您的代码中您只准备了一项,没有循环来收集所有写入的项。

关于java - 如何将java序列化对象写入和读取到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17293991/

相关文章:

java - 注释异常 : Use of @OneToMany or @ManyToMany targeting an unmapped class:

c++ - ifstream.eof() 在 C++ 中未评估为真

c++ - 从其他程序隐藏文件

javascript - Passport JS : Is it possible to not serialize a user when connecting an account?

c# - C#中的序列化和Java中的反序列化

java - 在闭包模板中使用主布局模板

java - 使 IntelliJ 标记所有参数而不仅仅是字符串参数

java - 确定 quartz 触发器的暂停状态?

linux - 文件夹中最近的文件

java - Scala 套接字无法写入输出流