← 中文资源

简体中文版本

FileChannel 分块读取文件

FileChannel.read 配 8 字节 ByteBuffer 分块读文件:read 后 flip 进入读模式解码输出,clear 复位回写模式继续读,循环到 read 返回 -1,不必把整个文件读进内存。

阅读英文原文

实现说明

FileChannel 分块读取文件可以归结为类 ChunkedFileReader。 迭代发生在 while (channel.read(buffer) != -1) { // 写模式:通道读入 buffer 内部——循环之外的语句只执行一遍。资源声明在 try-with-resources 头部,任何退出路径都会自动关闭,无需 finally 块。

常见问题

「FileChannel 分块读取文件」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

核心语句

Files.writeString(log, "start\nmiddle\nend\n", StandardCharsets.UTF_8);
Path log = Files.createTempFile("events-", ".log");
ByteBuffer buffer = ByteBuffer.allocate(8);

代码示例

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class ChunkedFileReader {

    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("events-", ".log");
        Files.writeString(log, "start\nmiddle\nend\n", StandardCharsets.UTF_8);

        try (FileChannel channel = FileChannel.open(log, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(8);
            while (channel.read(buffer) != -1) { // 写模式:通道读入 buffer
                buffer.flip(); // 切换到读模式
                System.out.print(StandardCharsets.UTF_8.decode(buffer));
                buffer.clear(); // 复位回写模式继续读
            }
        }
        Files.deleteIfExists(log);
    }
}