我们要读取或者修改的文件过大而不能放入内存时,使用内存映射文件就能帮我们来进行修改和读取。 这时我们完全可以假定整个文件已经被放入内存,而且完全可以把它当作一个很大的数组来访问
package com.mfs.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class LargeMappedFiles {
private static final int LENGTH = 1024 * 1024 * 128;
@SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException, IOException {
MappedByteBuffer map = new RandomAccessFile(new File("resource/LargeMappedFiles.resource"), "rw")
.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
int i = 0;
while (i < LENGTH) {
map.put((byte)'a');
i ++;
}
map.flip();
while (map.hasRemaining()) {
System.out.println(map.get());
}
}
}