Workshop
本页目录· 5 条
10.1 File I/O Activity: Employee records
The provided file employees.txt contains details of employees. Each record on the file contains details of one single employee. An employee has the following fields: employeeType, employeeNumber, name. These fields are separated by commas.
The aim of today's Workshop is to create a program that is able to read this file, store the information in a useful data structure, and output that information to a new file. You should work together in groups, planning and discussing your program design before writing it together. Make sure each person in your group gets a copy of any code you write before the workshop finishes, so that if you don't complete all the tasks today, you can complete it individually in your own time.
Task 1 - Discussion
Firstly, in your groups, brainstorm what kinds of problems might be encountered by a program when attempting to read the information in this file. What errors could potentially occur? How should the program recover from these errors?
Write down each of the different potential errors you come up with, as well as a good recovery strategy for each one.
Task 2 - Class Design and implementation
Draw a class diagram for the program with two classes: Employee, which represents an employee record as described above, and EmployeeList, which holds an ArrayList of Employee objects. Make sure you describe all the fields and methods each of these classes will need.
Now, start writing Java code to implement the Employee and EmployeeList classes according to the details in your class diagram.
Task 3 - readFile() method
In the EmployeeList class, write a method named readFile() that reads in the employee details from the file employees.txt and stores them in the ArrayList attribute - in other words, fills up the ArrayList of Employee with data read from the file. Refer back to the examples in Lesson 10.2 as needed to remind yourself how to read from a file in Java. Remember to include code to handle any checked exceptions that are thrown by the methods you call.
Hints:
- You should use a loop when reading from the file.
- You will probably need to use the split() method from the String class in your code to extract the three parts on each input line to create the Employee objects.
Now, write another method in the EmployeeList class to display on the screen the contents of the ArrayList of Employee attribute created in Task 2. Use this to test if your readFile() method works as specified.
Task 4 - writeFile() method
Write another method in the EmployeeList class named writeFile(), that writes all the employee details stored in the ArrayList attribute to a text file named output.txt. The format of the file should be the same as employees.txt. You should use a loop for this process.
Examine the contents of output.txt to check if your writeFile() method works as specified.