If you are going to use multiple appended ObjectOutputStreams, then I believe this might help (along with making sure you delete the file each time you run your test!):
Why can't a file that contains multiple appended ObjectOutputStreams be deserialized by one ObjectInputStream?
Using the default implementation of serialization, there must be a
one-to-one mapping between ObjectOutputStream construction and
ObjectInputStream construction. ObjectOutputStream constructor
writes a stream header and ObjectInputStream reads this stream
header. A workaround is to subclass ObjectOutputStream and override
writeStreamHeader(). The overriding writeStreamHeader() should
call the super writeStreamHeader method if it is the first write to
the file and it should call ObjectOutputStream.reset() if it is
appending to a pre-existing ObjectOutputStream within the file.
Otherwise I would suggest you add the objects to a List and then serialize it with a single ObjectOutputStream.
For example:
Vehicule v1 = new Vehicule();
Vehicule v2 = new Vehicule();
List vehicules = Arrays.asList(v1, v2);
// serialize the list of Vehicules
File f = new File("vehicule.txt");
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(f));
oos.writeObject(vehicules);
oos.close();
} catch (Exception e) {
e.printStackTrace(); // handle this appropriately
}
// deserialize the list of Vehicules
try {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(f));
List deserializedVehicles = (List) ois.readObject();
ois.close();
System.out.println("list size = " + deserializedVehicles.size());
} catch (Exception e) {
e.printStackTrace(); // handle this appropriately
}
For me, this outputs:
list size = 2