HashMap类型数据读写文件

来源:互联网 发布:淘宝店图片怎么制作的 编辑:程序博客网 时间:2024/06/10 18:39

直接转的论坛中别人的算法,直接上代码,做个笔记。

import java.util.*;import java.io.*;class Student implements Serializable {    int num;    String name;    double scores[]; // 三门课程成绩    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 {    @SuppressWarnings("unchecked")    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(stu);        oos.flush();        oos.close();        // 读        FileInputStream fis = null;        ObjectInputStream ois = null;        fis = new FileInputStream(file);        ois = new ObjectInputStream(fis);        HashMap<Integer, Student> stuRead = new HashMap<Integer, Student>();        stuRead = (HashMap<Integer, Student>) ois.readObject();        ois.close();        // 测试        for (Map.Entry<Integer, Student> item : stuRead.entrySet()) {            System.out.println(item.getValue());        }    }}

该代码属于字节流,所以用记事本打开会乱码,不影响代码操作。

参考资料:如何将HashMap中的内容写入到文件?

原创粉丝点击