日期:2014-05-20 浏览次数:20865 次
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; import java.util.HashMap; import java.util.Map; public class Test { public static void main(String args[]) { writer();//自己可以注释掉代码试试 reader(); } public static void writer(){ Map<Integer,Student> students=new HashMap<Integer,Student>(); students.put(1, new Student("A")); students.put(2, new Student("B")); File stuInfo = new File("stuInfo.txt"); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream( new FileOutputStream(stuInfo)); oos.writeObject(students); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { oos.flush(); oos.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void reader(){ Map<Integer,Student> students= null; File stuInfo = new File("stuInfo.txt"); ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream(stuInfo)); Object o = ois.readObject(); students = (Map<Integer,Student>)o; System.out.println(students); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally{ try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } } class Student implements Serializable{ Student(String name){ this.name = name; } private String name; @Override public String toString(){ return "Student name:"+name; } }
------解决方案--------------------
你真狠。。。看看你的构造函数:
Test(File stuinfo){
this.stuinfo=stuinfo;
try {
oos = new ObjectOutputStream(new FileOutputStream(stuinfo));
直接就用把FileOutputStream这个文件的内容清空了。。。