读写操作有问题,好像已经写进去了,但是读不到,不知道为什么
代码如下:package test;//题目:完成一个学生管理程序,使用学号作为键添加5个学生对象,并可以将全部的信息保存在文件中,
//可以实现对学生信息的全面查找,输出全部学生信息的功能。
//
import java.util.*;
import java.io.*;class Student implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 1L;
public int num;
public String name;
public double scores[]; // 三门课程成绩
public double aver; // 平均成绩 public Student() {
this.scores = new double[3];
} public Student(int num, String name, double score1, double score2,
double score3) {
this();
this.setNumber(num);
this.setName(name);
this.setScores(score1, score2, score3);
this.aver = (this.scores[0] + this.scores[1] + this.scores[2]) / 3;
} public void setNumber(int num) {
this.num = num;
} public void setName(String name) {
this.name = name;
} public void setScores(double score1, double score2, double score3) {
this.scores[0] = score1;
this.scores[1] = score2;
this.scores[2] = score3;
} public int getNumber() {
return num;
} public String getName() {
return name;
} public double[] getScores() {
return scores;
} public double getAver() {
return aver;
} public String toString() {
return "学号:" + this.num + "姓名:" + this.name + "\n" + "成绩————>" + "语文:"
+ this.scores[0] + "数学:" + this.scores[1] + "英语:"
+ this.scores[2] + "平均成绩:" + this.aver;
}
}/*
 * Scanner sc=new Scanner(System.in); sc.next()即为输入的内容;
 */
public class Test_12 {
public static void main(String[] args) throws Exception {
HashMap<Integer, Student> stu = new HashMap<Integer, Student>();
File file = new File("Stu_info.obj");
Student zhangsan = new Student(18, "张三", 78, 85, 92);
Student lisi = new Student(15, "李四", 85, 87, 74);
Student wangwu = new Student(20, "王五", 75, 98, 96);
Student zhaoliu = new Student(9, "赵六", 93, 98, 93);
stu.put(18, zhangsan);
stu.put(15, lisi);
stu.put(20, wangwu);
stu.put(9, zhaoliu); // 写
FileOutputStream fos = null;
ObjectOutputStream oos = null;
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
oos.writeObject(new Inner(stu));
oos.flush();
oos.close(); // 读
FileInputStream fis = null;
ObjectInputStream ois = null;
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
HashMap<Integer, Student> stuRead = null;
//如果读取的对象所属的类是Inner的子类,就···
if (Inner.class.isAssignableFrom(ois.readObject().getClass())) {
Inner inner = null;
try {
inner = (Inner) ois.readObject();//!!!!!!
} catch (EOFException e) {
System.out.println("eof");
ois.close();
}
stuRead = inner.stu;//空指针异常,其实就是inner = (Inner) ois.readObject();读不到数据,求解为什么
} // 测试
for (Map.Entry<Integer, Student> item : stuRead.entrySet()) {
System.out.println(item.getValue());
}
}
}class Inner implements Serializable {
/**
 * 这个类的初衷是想将前面获得的HashMap作为对象属性进行序列化,因为如果直接将Hashmap序列化的话
 * 在读取文件的时候(readobject),进行强制类型转换时,涉及到泛型,会报unchecked警告··· 仅此而已··
 */
private static final long serialVersionUID = 2L;
public HashMap<Integer, Student> stu; public Inner(HashMap<Integer, Student> stu) {
this.stu = stu;
}
}// 怎么将HashMap中的内容保存到文件,又怎么读取文件?希望各位朋友给点意见或思路.
readobjec空指针异常