If you want to store objects in a file, I'd advise you use object serialization. This link has useful details on how to serialise and deserialise a list
This is how you serialize a list:
ArrayList<Vehicle> vehicles= new ArrayList<>();
vehicles.add(new Vehicle());
vehicles.add(new Bike());
vehicles.add(new Car());
try
{
FileOutputStream fos = new FileOutputStream("vehiclesData");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(vehicles);
oos.close();
fos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
To deserialize use the following:
ArrayList<Vehicle> vehicles= new ArrayList<>();
try
{
FileInputStream fis = new FileInputStream("vehiclesData");
ObjectInputStream ois = new ObjectInputStream(fis);
vehicles= (ArrayList) ois.readObject();
ois.close();
fis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
return;
}
catch (ClassNotFoundException c)
{
System.out.println("Class not found");
c.printStackTrace();
return;
}
//Verify list data
for (Vehicle vehicle : vehicles) {
System.out.println(vehicle);
}
Make sure all your classes implement serializable
interface