Java二进制文件示例

Java二进制文件示例

通过以下案例具体说明如何将数据存入二进制文件以及如何读取二进制文件。

问题:输入5个学生的信息(包含学号、姓名、3科成绩),统计各学生的总分,然后将学生信息和统计结果存入二进制数据文件STUDENT.DAT中。从STUDENT.DAT文件中读取数据,寻找平均分最高的学生,并输出该学生的所有信息。

解答:

import java.io.*;

class Student {
    private String number, name;
    private double[] scores = new double[3];
    private double totalScore;

    public static final int NAME_SIZE = 40;
    public static final int NUMBER_SIZE = 20;
    public static final int RECORD_SIZE = 2 * NAME_SIZE + 2 * NUMBER_SIZE + 8 + 8 + 8 + 8;

    Student() {
    }

    Student(String num, String nam, double s0, double s1, double s2) {
        number = num;
        name = nam;
        scores[0] = s0;
        scores[1] = s1;
        scores[2] = s2;
        totalScore = s0 + s1 + s2;
    }

    public String getName() {
        return name;
    }

    public String getNumber() {
        return number;
    }

    public double getScores1() {
        return scores[0];
    }

    public double getScores2() {
        return scores[1];
    }
    public double getScores3() {
        return scores[2];
    }

    public double getTotalScore() {
        return totalScore=scores[0]+scores[1]+scores[2];
    }

    @Override
    public String toString() {
        return getClass().getName()
                + "[number=" + number
                + ",name=" + name
                + ",score1=" + scores[0]
                + ",score2=" + scores[1]
                + ",score3=" + scores[2]
                + ",totalScore=" + getTotalScore()
                + "]";
    }

    public void writeData(DataOutput out) throws IOException {
        DataIO.writeFixedString(number, NUMBER_SIZE, out);
        DataIO.writeFixedString(name, NAME_SIZE, out);
        out.writeDouble(scores[0]);
        out.writeDouble(scores[1]);
        out.writeDouble(scores[2]);
        out.writeDouble(totalScore);
    }

    public void readData(DataInput in) throws IOException {
        number = DataIO.readFixedString(NUMBER_SIZE, in);
        name = DataIO.readFixedString(NAME_SIZE, in);
        scores[0] = in.readDouble();
        scores[1] = in.readDouble();
        scores[2] = in.readDouble();
        totalScore = in.readDouble();
    }
}
public class Test {
    public static void main(String[] args) {
        Student[] s = new Student[5];
        s[0] = new Student("1", "小明", 78, 79, 80);
        s[1] = new Student("2", "小王", 88, 89, 90);
        s[2] = new Student("3", "小李", 98, 99, 100);
        s[3] = new Student("4", "小张", 108, 109, 110);
        s[4] = new Student("5", "小赵", 118, 119, 120);

        try {
            DataOutputStream out = new DataOutputStream(new FileOutputStream("STUDENT.DAT"));
            for (Student stu : s) {
                stu.writeData(out);
            }
            out.close();
            RandomAccessFile in = new RandomAccessFile("STUDENT.DAT", "r");
            int n = (int) (in.length() / Student.RECORD_SIZE);
            Student[] newStudent = new Student[n];
            for (int i = n - 1; i >= 0; i--) {
                newStudent[i] = new Student();
                in.seek(i * Student.RECORD_SIZE);
                newStudent[i].readData(in);
            }
            in.close();
            double highestScore = 0;
            int index = 0;
            for (int i = 0; i < n; i++) {
                if (newStudent[i].getTotalScore() > highestScore) {
                    index = i;
                }
            }
            System.out.println("The highest average one is " + newStudent[index]);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class DataIO {
    public static String readFixedString(int size, DataInput in) throws IOException {
        //之前少写了size
        StringBuilder b = new StringBuilder(size);
        int i = 0;
        boolean more = true;
        while (more && i < size) {
            char ch = in.readChar();
            i++;
            if (ch == 0) {
                more = false;
            } else {
                b.append(ch);
            }
        }
        in.skipBytes(2 * (size - i));
        return b.toString();
    }

    public static void writeFixedString(String s, int size, DataOutput out) throws IOException {
        for (int i = 0; i < size; i++) {
            char ch = 0;
            if (i < s.length()) {
                ch = s.charAt(i);
            }
            out.writeChar(ch);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值