I'm having trouble writing an ArrayList of a custom class to a file. I'm using
public static void SaveEmployees() throws FileNotFoundException, IOException{
ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream("magicscheduleEmp.sav");
save.writeObject(employeeList);
save.close();
}
Where employeeList is declared and initialized as an ArrayList of Employees (my class) in the main method. I have definitely added objects to employeeList, but calling SaveEmployees writes an empty ArrayList to the file. The Employee class is serializable.
What am I doing wrong?
Edit: employeeList is initialized here (in the main method)
public static ArrayList<Employee> employeeList = new ArrayList<>();
and populated through user input (in another jFrame class)
if(MainUI.addempcheck == true){
Employee newEmployee = new Employee(LastName.getText(), FirstName.getText());
newEmployee.position = EmpType.getSelectedItem().toString();
MainUI.employeeList.add(newEmployee);
MainUI.listModel.addElement(newEmployee.writeName().toString());
}
try {
MainUI.SaveEmployees();
} catch (FileNotFoundException ex) {
Logger.getLogger(NewEmployeeUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NewEmployeeUI.class.getName()).log(Level.SEVERE, null, ex);
}
this.dispose();
I have a button which prints the contents of employeeList, and shows that the list is populated before I save it. Maybe it's a problem with calling SaveEmployees?
employeeListis initialized and populated. It must be a static field in your example.ArrayListto back yourList<Employee> employeeListand you're sure yourEmployeeclass implementsSerializable, thenemployeeListis empty.BufferedOutputStreamto wrap theFileOutputStream.