0

I am creating a program that keeps track of employees. I have an ArrayList that keeps track of the current employees. Since ArrayLists aren't preserved after the program restarts I needed to find a way to preserve the employee list. I decided to create a file that had a list of all the employees then every time the program ran it would import the file into an ArrayList. I created a save method and an addEmployee method and this is what I have so far:

Code to create new employee (not addEmployee method):

System.out.println("Please enter the new employee's first name:");
firstName = addEmployee.nextLine();
System.out.println("Please enter the new employee's last name");
lastName = addEmployee.nextLine();
addEmployee(firstName, lastName); //calling the addEmployee method
save("employeetest"); //saving the array

Save method:

public static void save(String fileName) throws FileNotFoundException {
    String tmp = employees.toString();
    PrintWriter pw = new PrintWriter(new FileOutputStream(fileName,true));
    pw.write(tmp);
    pw.close();
}

The problem is every time you create a new employee it saves the entire ArrayList again, not just the employees name. So I decided to load just the name of the employee (as a string) at the end of the file. But now I need to load the file of Strings into an ArrayList. How should I convert the Strings from the file into an ArrayList and then load it into the ArrayList?

t0xic
  • 131
  • 1
  • 2
  • 9

1 Answers1

0

What you can do is to serialize the array. You can read about that here.

http://beginnersbook.com/2013/12/how-to-serialize-arraylist-in-java/

It will solve your problem if you use it this way:
When you start the program de-serialize the array stored in the file. When you quit the program, run your save method (which should be adjusted to serialize your arraylist to the file.

MajorT
  • 221
  • 1
  • 12
  • The problem is in the file there is not an array. There are strins. I need to convert all of those strings into an ArrayList (1 string is 1 item in the ArrayList) – t0xic Jan 04 '15 at 01:24
  • So I assume that you use the file for other purposes than persistency then? If you want just Strings in your file you can read it in like so: http://stackoverflow.com/questions/5343689/java-reading-a-file-into-an-arraylist If you don't use the file for something else then just storing your arraylist, it might be a good idea to change your code. This post covers it nicely http://stackoverflow.com/questions/15574168/how-to-write-and-retrieve-objects-arraylist-to-file – MajorT Jan 04 '15 at 10:46