在Java中如何读取二进制文件内容

使用FileInputStream或BufferedInputStream读取二进制文件,避免字符流导致数据损坏。1. FileInputStream适合小文件,逐字节读取并以十六进制输出;2. BufferedInputStream结合FileInputStream提升大文件读取效率,通过缓冲区批量读取字节。

在Java中读取二进制文件内容,通常使用字节流类 FileInputStream 或结合 BufferedInputStream 提高效率。由于二进制文件不是文本,不能用字符流直接处理,避免数据损坏。

1. 使用 FileInputStream 读取二进制文件

这是最基本的方式,适合小文件:

import java.io.FileInputStream;
import java.io.IOException;

public class ReadBinaryFile {
    public static void main(String[] args) {
        String filePath = "data.bin"; // 二进制文件路径
        try (FileInputStream fis = new FileInputStream(filePath)) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.printf("%02X ", data); // 以十六进制打印每个字节
            }
        } catch (IOException e) {
            System.err.println("读取文件出错:" + e.getMessage());
        }
    }
}

说明:每次调用 read() 返回一个字节(0-255),返回 -1 表示文件结束。适合逐字节处理,但效率较低。

2. 使用 BufferedInputStream 提高性能

对于大文件,建议配合缓冲流减少I/O操作次数:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadBinaryWithBuffer {
    public static void main(String[] args) {
        String filePath = "large.bin";
        try (FileInputStream fis = new FileInputStream(filePath);
             BufferedInputStream bis = new BufferedInputStream(fis)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead =

bis.read(buffer)) != -1) { for (int i = 0; i < bytesRead; i++) { System.out.printf("%02X ", buffer[i] & 0xFF); } } } catch (IOException e) { System.err.println("读取失败:" + e.getMessage()); } } }

优点:一次读取多个字节到缓冲区,显著提升读取速度。buffer 大小可根据需要调整,如 4096、8192 等。

3. 直接读取为字节数组(适合小文件)

Java 7+ 可使用 Files.readAllBytes() 快速加载整个文件:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class ReadAllBytesExample {
    public static void main(String[] args) {
        String filePath = "small.bin";
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            for (byte b : bytes) {
                System.out.printf("%02X ", b & 0xFF);
            }
        } catch (IOException e) {
            System.err.println("读取异常:" + e.getMessage());
        }
    }
}

注意:此方法会一次性将整个文件加载到内存,只适用于小文件,否则可能引发 OutOfMemoryError。

关键点总结

读取二进制文件时需注意:

  • 始终使用字节流(InputStream),不要用 Reader 等字符流
  • 正确处理 IOException,包括文件不存在、权限不足等情况
  • 使用 try-with-resources 自动关闭资源
  • 若需解析特定格式(如图片、序列化对象),应在读取后按协议解析字节
基本上就这些。根据文件大小和性能需求选择合适的方法即可。