1 Service.java2
3 packagecn.employee_io;4
5 importjava.io.BufferedReader;6 importjava.io.File;7 importjava.io.FileOutputStream;8 importjava.io.FileReader;9 importjava.io.IOException;10 importjava.io.ObjectInputStream;11 importjava.io.ObjectOutputStream;12 importjava.util.LinkedList;13 importjava.util.List;14
15 public classService {16 List list = new LinkedList();17 File file = null;18 ObjectInputStream ois = null;19 ObjectOutputStream oos = null;20
21 public Service() throwsIOException, ClassNotFoundException {22 reader();23 }24
25 /**
26 * 读文件27 *@throwsIOException28 *@throwsClassNotFoundException29 */
30 public void reader() throwsIOException, ClassNotFoundException {31 /*file = new File("src/cn/employee_io/emp.txt");32 if (!file.exists()) {33 file.createNewFile();34 }35 ois = new ObjectInputStream(new FileInputStream(file));36 list = (List) ois.readObject(); // 给list赋值37 ois.close();*/
38 BufferedReader br=new BufferedReader(new FileReader("src/cn/employee_io/emp.txt"));39 String empStr=null;40 while((empStr=br.readLine())!=null){41 String[] empStrs=empStr.split(",");42 list.add(new Employee(empStrs[0],empStrs[1],Integer.parseInt(empStrs[2]),Double.parseDouble(empStrs[3])));43 }44 br.close();45 }46
47 /**
48 * 写文件49 *@throwsIOException50 *@throwsClassNotFoundException51 */
52 public void writer() throwsIOException, ClassNotFoundException {53 file = new File("src/cn/employee_io/emp.txt");54 if (!file.exists()) {55 file.createNewFile();56 }57 oos = new ObjectOutputStream(newFileOutputStream(file));58 for(Employee e:list){59 oos.writeObject(e.toString()+"\r\n"); //将list值写进文件里去
60 }61 oos.close();62 }63
64 /**
65 * 添加员工66 *@parame67 *@throwsClassNotFoundException68 *@throwsIOException69 */
70 public void add(Employee e) throwsClassNotFoundException, IOException {71 if (!list.contains(e)) {72 list.add(e);73 writer();74 System.out.println("添加成功!");75 } else{76 System.out.println("添加失败!");77 }78 }79
80 /**
81 * 查询所有员工82 */
83 public voidqueryAll(){84 System.out.println("编号 "+"姓名 "+"年龄 "+"薪资");85 for(Employee e:list){86 System.out.println(e.getEmpId()+" "+e.getName()+" "+e.getAge()+" "+e.getSalary());87 }88 }89
90 /**
91 * 查询单个员工92 *@paramempId93 */
94 public voidquery(String empId){95 for(int i=0;i
106 /**
107 * 删除员工108 *@throwsIOException109 *@throwsClassNotFoundException110 */
111 public void delete(String empId) throwsClassNotFoundException, IOException{112 for(int i=0;i
125 /**
126 * 修改员工127 *@throwsIOException128 *@throwsClassNotFoundException129 *130 */
131 public void update(Employee emp) throwsClassNotFoundException, IOException{132 for(int i=0;i