package cn.edu.bjut.textmining.chapter2; import cn.edu.bjut.textmining.util.FileUtil; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Path; public class MappedFileDemo { private static final int MAP_BYTES = 2048; private static final int PREVIEW_CHARS = 220; public static void main(String[] args) { Path path = FileUtil.path("data", "chapter2", "tang-poems-classics.txt"); try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "r"); FileChannel channel = file.getChannel()) { long fileSize = channel.size(); long mapSize = Math.min(fileSize, MAP_BYTES); MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, mapSize); String mappedText = StandardCharsets.UTF_8.decode(buffer).toString(); int previewEnd = Math.min(mappedText.length(), PREVIEW_CHARS); int lastLineBreak = mappedText.lastIndexOf('\n', previewEnd); if (lastLineBreak > 0) { previewEnd = lastLineBreak; } System.out.println("文件大小:" + fileSize + " 字节"); System.out.println("本次映射:" + mapSize + " 字节"); System.out.println("文件头部内容:"); System.out.println(mappedText.substring(0, previewEnd)); } catch (Exception e) { e.printStackTrace(); } } }