← 中文资源

简体中文版本

FileChannel 内存映射文件

用 FileChannel.map 得到 MappedByteBuffer:文件按内存方式按字节访问,扫描大文件不用经过堆缓冲逐块拷贝,只读映射足够覆盖检索场景。

阅读英文原文

实现说明

FileChannel 内存映射文件可以归结为类 MmapScan。 资源声明在 try-with-resources 头部,任何退出路径都会自动关闭,无需 finally 块。

使用要点

  • 每一步打印都带着自己的标签:file bytes:、mapped bytes:、has payment:。

常见问题

运行「FileChannel 内存映射文件」会打印什么?

运行文件本身,file bytes:、mapped bytes:、has payment: 这些前缀各对应一段演示逻辑。

核心语句

MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

代码示例

import java.io.IOException;
import java.nio.MappedByteBuffer;
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 MmapScan {

    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("events-", ".log");
        Files.writeString(log, "START\n2026-11-14 login alice\n2026-11-14 payment bob\nEND");
        long size = Files.size(log);

        try (FileChannel channel = FileChannel.open(log, StandardOpenOption.READ)) {
            // 只读映射:之后像访问内存数组一样按字节读文件,不再走 read 的堆拷贝
            MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

            String content = StandardCharsets.UTF_8.decode(map).toString();
            System.out.println("file bytes: " + size);
            System.out.println("mapped bytes: " + map.capacity());
            System.out.println("has payment: " + content.contains("payment"));
        }

        Files.deleteIfExists(log);
    }
}