practical quiz 9.employeefileio.java

来自「ssd3的全部答案」· Java 代码 · 共 83 行

JAVA
83
字号
import java.util.*;
import java.io.*;

/**
 * This class provides two file I/O methods for handling employee data.
 * 
 * @author Neil
 * @version 1.0.0
 * @see Employee
 */
public class EmployeeFileIO {

	/**
	 * Creates an <code>ArrayList</code> of <code>Employee</code> objects
	 * from a file that contains employee data.
	 * <p>
	 * Every line in the specified file should contain three fields: ID, name,
	 * and salary of an employee in the following format: ID_name_salary
	 * </p>
	 * 
	 * @param filename
	 *            the name of a file containing employee data.
	 * @return an <code>ArrayList</code> of <code>Employee</code> objects.
	 * @throws FileNotFoundException
	 *             if the specified file does not exist.
	 * @throws IOException
	 *             if an I/O error occurs.
	 * @throws NoSuchElementException
	 *             if the data in the file is incomplete.
	 * @throws NumberFormatException
	 *             if the file contains invalid numbers.
	 */
	public static ArrayList<Employee> read(String filename)
			throws FileNotFoundException, IOException, NoSuchElementException,
			NumberFormatException {

		BufferedReader fileIn = new BufferedReader(new FileReader(filename));
		StringTokenizer tknzr;
		ArrayList<Employee> result = new ArrayList<Employee>();

		String line = fileIn.readLine();

		while (line != null) {
			tknzr = new StringTokenizer(line, "_");
			result.add(new Employee(Integer.parseInt(tknzr.nextToken()), tknzr
					.nextToken(), Double.parseDouble(tknzr.nextToken())));
			line = fileIn.readLine();
		}

		fileIn.close();
		return result;
	}

	/**
	 * Creates a file of employee data from an <code>ArrayList</code> of
	 * <code>Employee</code> objects.
	 * <p>
	 * Every line in the file should contain the ID, name, and salary of an
	 * employee separated by an underscore: ID_name_salary
	 * </p>
	 * 
	 * @param filename
	 *            the name of the file that will store the employee data.
	 * @param arrayList
	 *            an <code>ArrayList</code> of <code>Employee</code>
	 *            objects.
	 * @throws IOException
	 *             if an I/O error occurs.
	 */
	public static void write(String filename, ArrayList<Employee> arrayList)
			throws IOException {

		PrintWriter fileOut = new PrintWriter(new FileWriter(filename));

		for (Iterator<Employee> i = arrayList.iterator(); i.hasNext();) {
			Employee temp = i.next();
			fileOut.println(temp.getId() + "_" + temp.getName() + "_"
					+ temp.getSalary());
		}

		fileOut.close();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?