import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class ObjectOperation{ public void save(Object obj,String path){ FileOutputStream fos = null ; ObjectOutputStream oos = null ; try { fos = new FileOutputStream(new File(path)); oos = new ObjectOutputStream(fos) ; oos.writeObject(obj) ; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { oos.flush() ; System.out.println("save success!"); } catch (IOException e) { e.printStackTrace(); }finally{ fos = null ; oos = null ; } } } public Object get(String path){ FileInputStream fis = null ; ObjectInputStream ois = null ; Object o = null ; try { fis = new FileInputStream(new File(path)) ; ois = new ObjectInputStream(fis) ; o = ois.readObject() ; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally{ fis = null; ois = null ; } return o ; } public static void main(String[] args) { Good a = new Good() ; a.setLuckNumber(1949) ; Luck b = new Luck() ; b.setInfo(" 中国 ") ; a.setLuckNumber(b) ; String path = "D:"+File.separator+"a.txt" ; ObjectOperation ser = new ObjectOperation() ; ser.save(a,path) ; Good a1 = (Good) ser.get(path) ; System.out.println(" 幸运数字 :" + a1.getLuckNumber()) ; System.out.println(" 幸运人: " + a1.getLuck().getInfo()) ; } } class Good implements Serializable { private static final long serialVersionUID = -1234567891212L; private Luck luckMan ; private int luckNumber ; public Luck getLuck() { return luckMan; } public void setLuckNumber(Luck b) { this.luckMan = b; } public int getLuckNumber() { return luckNumber; } public void setLuckNumber(int aNumber) { this.luckNumber = aNumber; } } class Luck implements Serializable { private static final long serialVersionUID = -9876543210L; private String str ; public String getInfo() { return str; } public void setInfo(String str) { this.str = str; } } 程序运行结果: