这是我的hashMap
Map<Integer,Student> students=new HashMap<Integer,Student>();
当我向里面添加数据完了以后用:
stuInfo = new File("stuinfo.ser");
oos = new ObjectOutputStream( new FileOutputStream(stuInfo));
oos.writeObject(students);
oos.close();
将students序列化存在stuinfo.ser中没有问题,当我关闭程序重新读取时:
ois= new ObjectInputStream(new FileInputStream(stuInfo));
students=(Map<Integer, Student>) ois.readObject();
程序出现java.io.EOFException
当我没有关闭程序时在反序列化就可以,这是为什么?怎么解决!
我的目的是是想把在程序关闭时之前students保存下来,当下次打开程序再将它读取出来
求指教!
------解决方案--------------------
如下是测试代码,没有问题,我是疑惑楼主代码或许有问题。
- Java code
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这个文件的内容清空了。。。