0

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?

5
  • 4
    Show us how employeeList is initialized and populated. It must be a static field in your example. Commented Aug 22, 2013 at 17:19
  • Without seeing what is going on with arraylist, I can only recommend you to write each element separately, like shown in this example: stackoverflow.com/a/6548204/1276128 Commented Aug 22, 2013 at 17:24
  • 3
    If you're using an ArrayList to back your List<Employee> employeeList and you're sure your Employee class implements Serializable, then employeeList is empty. Commented Aug 22, 2013 at 17:26
  • 1
    You will have to give more of your code. I tried out an SSCCE and write and read works fine covering what you have exposed here. Employee class serializable, employeeList as static. Commented Aug 22, 2013 at 17:41
  • Are you positive the file is empty? Have you tried deserializing it and printing the results? It seems that nothing is wrong with your code. Maybe you could try using a BufferedOutputStream to wrap the FileOutputStream. Commented Aug 22, 2013 at 22:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.