402. Java 文件操作基础 - 读取二进制文件

0 阅读2分钟

402. Java 文件操作基础 - 读取二进制文件

1️⃣ 背景说明

  • 二进制文件(Binary File)与文本文件不同,它存储的数据不是可读字符,而是原始字节。
  • 读取二进制文件时,使用 InputStream,写入二进制文件时使用 OutputStream
  • 对二进制文件,不能用 readLine() 直接读取(它是字符流方法)。如果想逐行读取,可以将字节转换为字符(需知道编码)。

2️⃣ 读取二进制文件示例

import java.nio.file.*;
import java.io.*;

public class BinaryFileReadExample {

    public static void main(String[] args) {
        Path file = Paths.get("example.bin"); // 二进制文件路径

        // try-with-resources 自动关闭流
        try (InputStream in = Files.newInputStream(file)) {

            // 将输入流包装成 BufferedInputStream 提高效率
            BufferedInputStream bis = new BufferedInputStream(in);

            byte[] buffer = new byte[1024]; // 每次读取 1024 字节
            int bytesRead;

            while ((bytesRead = bis.read(buffer)) != -1) {
                // bytesRead 表示本次实际读取的字节数
                for (int i = 0; i < bytesRead; i++) {
                    System.out.printf("%02X ", buffer[i]); // 以十六进制打印
                }
                System.out.println();
            }

        } catch (IOException x) {
            System.err.println("读取文件异常: " + x);
        }
    }
}

🔹 说明

  1. Files.newInputStream(file) 返回一个 未缓冲的 InputStream
  2. 使用 BufferedInputStream 可以提高读取效率,减少 I/O 调用次数。
  3. 每次读取固定大小的字节数组(buffer),直到返回 -1 表示文件结束。
  4. 可将字节数组打印、保存或进行其他二进制处理。

3️⃣ 转换为字符流读取(可选)

如果二进制文件是文本数据,想按行读取,可像这样:

try (InputStream in = Files.newInputStream(file);
     BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException x) {
    System.err.println("读取文本文件异常: " + x);
}
  • InputStreamReader 将字节流转换为字符流,指定编码(如 UTF-8)。
  • BufferedReader 提供 readLine() 方法,可按行读取文本数据。

4️⃣ 总结

  • InputStream vs Reader
    • InputStream:读取原始字节 → 二进制文件
    • Reader:读取字符 → 文本文件
  • 缓冲流 BufferedInputStream / BufferedReader 提高效率
  • try-with-resources 自动关闭流,防止资源泄漏
  • 循环读取:用 read(buffer)readLine() 控制循环,处理大文件