Im trying to learn how to use an Array List to write objects to a file, however, the file keeps being overwritten and the data is not being kept when I restart the program:
System.out.println("Enter DVD title: ");
String title = inputScanner.nextLine();
System.out.println("Enter main actor: ");
String actor = inputScanner.nextLine();
System.out.println("Enter DVD's release year: ");
String yearOfRelease = inputScanner.nextLine();
newDVD = new DVD(title, actor, yearOfRelease);
System.out.println("Entered DVD details: ");
DVDCollection.add(newDVD);
writeDVDs(DVDCollection);
break;
Above code takes input from the user and stores it in an ArrayList.
When I restart the program it seems to wipe everything.
static void writeDVDs(ArrayList<DVD> DVDs) throws Exception {
try {
Boolean append = true;
FileOutputStream fileOutputStream = new FileOutputStream("DVDCollection.dat", append);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
for (int i = 0; i < DVDs.size(); i++){
DVD theDVD = DVDs.get(i);
objectOutputStream.writeObject(theDVD);
System.out.println("DVD successfully saved");
}
}
catch (Exception e){
System.out.println("Cant write data to file");
}
}