Memory Mapped File Via FileChannel Map
Map a file into memory with FileChannel.map and read it as a MappedByteBuffer, so large files are scanned without copying through heap buffers.
Code
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);
}
}Inside the snippet
Count the class MmapScan as the entire surface area of Memory Mapped File Via FileChannel Map.
The try-with-resources form guarantees each declared resource is closed even when the body throws.
Using it
The demo output is labeled (file bytes:, mapped bytes:, has payment:), so every printed line maps back to its originating operation.
Key statements
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
Interactive Tools for This Topic
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Memory Mapped File Via FileChannel Map print when run?
- No setup needed: run the file and look for labeled lines like `file bytes:`, `mapped bytes:`, `has payment:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.