I'm having difficulty writing and reading an array of objects from a file.
This is what 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; }
I use the basic GUI elements to enter input and save it as an object to a file ...
I use the following code to write to a file called test.dat with a reliable 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 a 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 can not read all the objects from the file, only the first one is shown, and it returns an IndexOutOfBounds exception: \ What am I doing wrong?
PS If the solution is obvious, do not worry, I have not slept for more than 24 hours: P
Thanks in advance! Nikola