How to store and read an array list of objects in java?

Nikola picture Nikola · Aug 8, 2010 · Viewed 36.4k times · Source

I am having difficulties w/ writing and reading an array of objects from a file.

This is how my object looks like:

package registar;

import java.io.Serializable;

public class Vozilo implements Serializable {

    private static final long serialVersionUID = -5302010108271068350L;

    private String registracija;
    private String marka;
    private String kategorija;
    private int kubikaza;

    public Vozilo(String registracija, String marka, String kategorija,
            int kubikaza) {
        super();
        this.registracija = registracija;
        this.marka = marka;
        this.kategorija = kategorija;
        this.kubikaza = kubikaza;
    }
/* ALL GETTERS AND SETTERS ARE BELOW */

I am using basic GUI elements to get input and store it as object into a file...

I'm using the following code to write to a file named "test.dat" w/ dependable flag:

final ObjectOutputStream fos = new ObjectOutputStream(new FileOutputStream("test.dat", true));

Vozilo novo = new Vozilo(txtRegistracija.getText(), txtMarka.getText(), cbKat.getSelectedItem().toString(), Integer.parseInt(txtKubikaza.getText()) );

try {
    fos.writeObject(novo);
    fos.close();
    JOptionPane.showMessageDialog(unos, "Car was added!");
} catch (IOException e) {
    e.printStackTrace();
    JOptionPane.showMessageDialog(unos, "Car was NOT added!");
}

And the following code to read from file:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.dat"));

ArrayList<Vozilo> list = new ArrayList<Vozilo>();
Vozilo vozilo = (Vozilo) ois.readObject();

list.add(vozilo);
ois.close();

for (Vozilo voz : list) {
    System.out.println("Marka: " + voz.getMarka() + "\n");
}

The problem is that I am unable to read all of the objects from file, only the first one is shown, and it iver returns IndexOutOfBounds exception :\ What am I doing wrong?

P.S. If the solution is obvious, don't bother, I haven't slept for more than 24hrs :P

Thank you in advance!!! Nikola

Answer

Andy Lin picture Andy Lin · Aug 8, 2010

You can add a loop as follows:

Object obj = null;
while ((obj = ois.readObject()) != null) {
    if (obj instanceof Vozilo) {
    Vozilo vozilo = (Vozilo) obj;
    list.add(vozilo);
    }
}

However, you need to deal with EOFException when it reaches the end of the file.

PS: please use close() in finally block :)