题目

演示二进制文件操作:先将包含 n 个整数的数组以纯二进制形式写入磁盘文件,随后再重新打开文件读回内存数组中,比对验证写入与读取的数据完全一致。

输入格式:第一行输入整数个数 n;第二行输入 n 个整数。

输出格式:读回验证成功输出 ok,数据不一致或读写失败输出 mismatch。

数据范围与约定:1 ≤ n ≤ 1000。

思路与算法

1. 二进制写入 fwrite
以 "wb" 模式打开文件,调用 fwrite(arr, sizeof(int), n, fp); 将整块内存数据按二进制字节序列直接落盘。

2. 二进制读回 fread
以 "rb" 模式打开文件,调用 fread(buf, sizeof(int), n, fp); 还原内存数据。二进制读写效率显著高于文本序列化解析。

完整程序

import java.io.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        if (!sc.hasNextInt()) return;
        int n = sc.nextInt();
        int[] original = new int[n];
        for (int i = 0; i < n; i++) {
            original[i] = sc.nextInt();
        }

        // 使用 ByteArrayOutputStream / DataOutputStream 模拟二进制流写入
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        try {
            for (int val : original) {
                dos.writeInt(val);
            }
            dos.flush();

            // 模拟二进制流读回验证
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DataInputStream dis = new DataInputStream(bais);
            boolean match = true;
            for (int i = 0; i < n; i++) {
                if (dis.readInt() != original[i]) {
                    match = false;
                    break;
                }
            }
            System.out.println(match ? "ok" : "mismatch");
        } catch (IOException e) {
            System.out.println("mismatch");
        }
    }
}

运行示例

输入:

3
10 20 30

输出:

ok