Marcello Fabrizio
Marcello Fabrizio

Reputation: 337

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

I'm trying to append an ArrayList to a binary file so I can save its data when the program is closed. The snippet below shows how I'm writing them

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();
        }
    }

I'm using the AppendableObjectOutputStream from this solution. And here is how I'm reading from the file

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;

    }

All the data I write in the first time is read correctly. But when the new data should be appended, only the first information is returned, and I can't figure out what's causing this.

Upvotes: 0

Views: 112

Answers (1)

Joni
Joni

Reputation: 111329

If you add a new object to the file this way, it will be a new object, separate from other objects already in the file. It's not adding more items to the ArrayList you wrote before.

If you have written two objects to the file you have to call readObject twice to get them both. If the two happen to be lists, you can merge them into a single list with a call to add all:

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

If you have appended more than one object, you may need a loop to read them all.

Upvotes: 2

Related Questions