繁体   English   中英

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

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

我正在尝试将 append 和 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();
        }
    }

我正在使用解决方案中的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;

    }

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

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

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

readDealerships = new ArrayList();
readDealerships.addAll((ArrayList<Dealership>) or.readObject());
readDealerships.addAll((ArrayList<Dealership>) or.readObject());

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM