题目

把 n 个整数写入DataInputStream再读回验证

思路

读 n 与 n 个整数,用 BytesIO 写入二进制再读回比较,与 C 的 fwrite/fread 思路相同。

解题分析

struct.pack/unpack 负责 int 与 bytes 互转;先写长度再写数据,读回时才能知道数组有多长。在线用内存缓冲区,本地可改为 open(..., "wb"/"rb")。

函数简要说明

二进制写入再读回(与 C fwrite/fread 对应):

  • DataOutputStream.writeInt(x):按 4 字节写 int;DataInputStream.readInt() 对称读取。
  • ByteArrayOutputStream:在内存中积累字节,toByteArray() 再交给 DataInputStream 读回,便于在线运行。
  • FileOutputStream / FileInputStream:写读磁盘上的 .bin 文件。

完整程序

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        int n = 3;
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = 10;
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(bos);
        out.writeInt(n);
        for (int v : a) {
            out.writeInt(v);
        }
        DataInputStream in = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
        int m = in.readInt();
        int[] b = new int[m];
        for (int i = 0; i < m; i++) {
            b[i] = in.readInt();
        }
        boolean ok = m == n;
        for (int i = 0; ok && i < n; i++) {
            if (a[i] != b[i]) {
                ok = false;
            }
        }
        System.out.println(ok ? "ok" : "fail");
    }
}

运行示例

输出:

ok