- 关键步骤:
- 打开文件通道:通过
FileInputStream
或RandomAccessFile
获取文件对应的FileChannel
。
- 创建内存映射:调用
FileChannel
的map
方法,将文件内容映射到内存中,返回一个MappedByteBuffer
。
- 读取数据:使用
MappedByteBuffer
读取数据。
- 代码示例:
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MemoryMappedFileReader {
public static void main(String[] args) {
String filePath = "largeTextFile.txt";
try (FileInputStream fis = new FileInputStream(filePath);
FileChannel channel = fis.getChannel()) {
// 获取文件大小
long fileSize = channel.size();
// 将文件映射到内存
MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
// 读取数据
byte[] buffer = new byte[(int) fileSize];
mbb.get(buffer);
String content = new String(buffer);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}