需求:將 int[] arr = {12, 14, 21, 34, 24, 35} 寫入 temp.dat,再讀出並反序顯示 {35, 24, 34, 21, 14, 12}。
import java.io.*;
import java.util.Arrays;
public class ArrayFileDemo {
static final String FILE = "temp.dat";
public static void main(String[] args) throws IOException {
int[] src = {12, 14, 21, 34, 24, 35};
// 1. 寫入 (DataOutputStream 保證跨平台二進位格式)
try (DataOutputStream out = new DataOutputStream(new FileOutputStream(FILE))) {
for (int v : src) out.writeInt(v);
}
// 2. 讀入陣列
int[] dst = new int[src.length];
try (DataInputStream in = new DataInputStream(new FileInputStream(FILE))) {
for (int i = 0; i < dst.length; i++) dst[i] = in.readInt();
}
// 3. 反序輸出
System.out.print("反序結果: {");
for (int i = dst.length - 1; i >= 0; --i) {
System.out.print(dst[i] + (i > 0 ? ", " : "}\n"));
}
}
}
DataOutputStream/DataInputStream 處理基本型別二進位讀寫,避免文本解析開銷。try-with-resources 自動關閉流,防止資源洩漏。此範例展示 Java 二進位 IO 的標準用法,適合作為檔案處理教學模板。