title: How to store and read an array list of objects in java?
body: <p>I am having difficulties w/ writing and reading an array of objects from a file.</p>
  
  <p>This is how my object looks like:</p>
  
  <pre><code>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 */
  </code></pre>
  
  <p>I am using basic GUI elements to get input and store it as object into a file...</p>
  
  <p>I'm using the following code to write to a file named "test.dat" w/ dependable flag:</p>
  
  <pre><code>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!");
  }
  </code></pre>
  
  <p>And the following code to read from file:</p>
  
  <pre><code>ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.dat"));
  
  ArrayList&lt;Vozilo&gt; list = new ArrayList&lt;Vozilo&gt;();
  Vozilo vozilo = (Vozilo) ois.readObject();
  
  list.add(vozilo);
  ois.close();
  
  for (Vozilo voz : list) {
      System.out.println("Marka: " + voz.getMarka() + "\n");
  }
  </code></pre>
  
  <p>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>
  
  <p><em>P.S. If the solution is obvious, don't bother, I haven't slept for more than 24hrs :P</em></p>
  
  <p>Thank you in advance!!!
  Nikola</p>