雇员类
package io; import java.io.Serializable; @SuppressWarnings("serial") public class Emp implements Serializable{ private Integer empno; private String ename; private String job; private double comm; private double sal; public Integer getEmpno() { return empno; } public void setEmpno(Integer empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public double getComm() { return comm; } public void setComm(double comm) { this.comm = comm; } public double getSal() { return sal; } public void setSal(double sal) { this.sal = sal; } @Override public String toString() { return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job + ", comm=" + comm + ", sal=" + sal + "]"; } }
对象操作工具类
package io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class FileOperate { private File file = null; //通过外部设置文件路径 public FileOperate(File file){ //可以直接接收File对象 this.file = file; } public FileOperate (String path){ this(new File(path)); } /** * * 保存对象信息 * * @param obj * @throws Exception */ public void save(Object obj) throws Exception{ ObjectOutputStream oos = null; try{ if(!this.file.getParentFile().exists()){ this.file.getParentFile().mkdirs(); } oos = new ObjectOutputStream(new FileOutputStream(this.file)); oos.writeObject(obj); }catch(Exception e){ throw e; }finally{ if(oos != null){ oos.close(); } } } /** * * 输出对象信息 * * @return * @throws Exception */ public Object load() throws Exception{ ObjectInputStream ois = null; try{ ois = new ObjectInputStream(new FileInputStream(this.file)); return ois.readObject(); }catch(Exception e){ throw e; }finally{ if(ois != null){ ois.close(); } } } }
菜单类
package io; import java.io.File; public class EmpMenu { private static final String PATH = "d:" + File.separator + "mydemo"; public void init(){ //对象初始化 Emp vo = new Emp(); vo.setEmpno(7369); vo.setEname("SMITH"); vo.setJob("CLERK"); vo.setSal(800.0); vo.setComm(0.0); FileOperate fo = new FileOperate(PATH); try { fo.save(vo); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void read(){ //读取对象信息 FileOperate fo = new FileOperate(PATH); try{ Emp emp = (Emp)fo.load(); System.out.println(emp); }catch(Exception e){ e.printStackTrace(); } } public void change(){ //保存对象信息 FileOperate fo = new FileOperate(PATH); try{ Emp emp = (Emp)fo.load(); emp.setEname("张三"); emp.setSal(1000.0); System.out.println(emp); }catch(Exception e){ e.printStackTrace(); } } }
测试类
package io; public class TestEmpMenu { public static void main(String[] args) { EmpMenu em = new EmpMenu(); //em.init(); em.change(); em.read(); } }