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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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)
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: stackoverflow.com/questions/5343689/… 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 stackoverflow.com/questions/15574168/…

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.