数据不会附加到带有 ObjectOutputStream 的二进制文件的末尾

Data won't append to the end of a binary file with ObjectOutputStream

我正在尝试将 ArrayList 附加到二进制文件,以便在程序关闭时保存其数据。下面的代码片段显示了我是如何写的

public void writeInFile(String filePath, ArrayList<Dealership> dealershipList, boolean append) {
        File file = new File(filePath);
        ObjectOutputStream oos = null;
        FileOutputStream fos = null;

        try {
            if (!file.exists() || !append) oos = new ObjectOutputStream (new FileOutputStream (file));
            else oos = new AppendableObjectOutputStream (new FileOutputStream (file, append));
            oos.writeObject(dealershipList);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

我正在使用 this 中的 AppendableObjectOutputStream 解决方案。这是我从文件

中读取的方式
public ArrayList<Dealership> readDealeshipFromFile(String filePath) {
        ArrayList<Dealership> readDealerships = new ArrayList<Dealership>();

        try {
            FileInputStream fis = new FileInputStream(filePath);
            ObjectInputStream ois = new ObjectInputStream(fi);
            readDealerships = (ArrayList<Dealership>) or.readObject();
            or.close();
            fi.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return readDealerships;

    }

我第一次写入的所有数据都被正确读取了。但是当应该附加新数据时,只返回第一条信息,我不知道是什么原因造成的。

如果您以这种方式向文件添加新对象,它将是一个新对象,与文件中已有的其他对象分开。它不会向您之前编写的 ArrayList 添加更多项目。

如果您向文件写入了两个对象,则必须调用两次 readObject 才能同时获取它们。如果这两个恰好是列表,您可以通过调用 add all:

将它们合并到一个列表中
readDealerships = new ArrayList();
readDealerships.addAll((ArrayList<Dealership>) or.readObject());
readDealerships.addAll((ArrayList<Dealership>) or.readObject());

如果您附加了多个对象,您可能需要一个循环来读取它们。