I have several objects which are assigned attributes based on user input. I then store those objects in a vector, and then write that vector to a file but on deserializing the stored vector, only the first object is read. Here’s the code that i have so far:
public Vector<Cases> registerCase() {
Vector<Cases> casesVector = new Vector<Cases>(10, 2);
Scanner myCase = new Scanner(System.in);
Scanner userChoice = new Scanner(System.in);
System.out.println("HOW MANY CASES DO YOU WANT TO REGISTER?");
int count = userChoice.nextInt();
for (int i = 0; i < count; i++) {
Cases newCase = new Cases();
System.out.println("Enter the case name: ");
newCase.caseName = myCase.nextLine();
System.out.println("Enter the client's name: ");
newCase.client = myCase.nextLine();
System.out.println("Enter the case type: ");
newCase.caseType = myCase.nextLine();
if((newCase.caseType.equals("Major")) || newCase.caseType.equals("major")){
newCase.closedCaseRevenue = majorCasePrice;
}else {
newCase.closedCaseRevenue = (int) (0.75 * majorCasePrice);
}
casesVector.add(newCase);
}
try{
// Open a file to write to, named SavedCases.sav.
FileOutputStream saveFile = new FileOutputStream("SavedCases.sav", true);
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(casesVector);
save.close();
}
catch(Exception exc){
exc.printStackTrace();
}
Vector<Cases> comVector = new Vector<Cases>();
try{
FileInputStream saveFile = new FileInputStream("SavedCases.sav");
ObjectInputStream save = new ObjectInputStream(saveFile);
comVector = (Vector<Cases>) save.readObject();
System.out.println("The size of the vector is: " + comVector.size());
save.close(); // This also closes saveFile.
}
catch(Exception exc){
exc.printStackTrace();
}
for (Cases law_case : comVector) {
System.out.println("Name: " + law_case.caseName);
System.out.println("Client: " + law_case.client);
System.out.println("Case Type: " + law_case.caseType);
System.out.println("Case State: " + law_case.caseState);
System.out.println("Case Revenue: " + law_case.closedCaseRevenue);
System.out.println();
}
return casesVector;
}
EDIT: So to append to a vector if it already exists…
Check for an existing file using
Then read in your input and output it exactly as you have it there, however when you make the FileOutputStream do not include the true flag, this will cause you to add a new vector each time instead of just overwriting the current vector with the new, correct one.
ORIGINAL
The problem is with your implementation is that you are appending a new array each time you write to the save file. So whenever you try to read from the file, you are always getting that first array you ever made.
I am not sure whether you’d like to just overwrite the array with a new one each time, but you should either read in the current array before you add more cases or not set the append flag to true for the FileWriter constructor depending on your desired result.