利用文件的内存映射可以实现文件的快速读写,原理为把文件映射到内存,对内存的操作相当于对文件的操作,速度快但硬件消耗较大,尤其是内存。
具体代码如下:
package test;
import java.io.File;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MappedByteBufferTest {
public static void main(String[] args) throws Exception {
File file = new File("e:"+File.separator+"abc.txt");
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
//获得文件的内存映射
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
byte[] tmp = new byte[(int) file.length()];
int count=0;
//读入到内存数组
while(mbb.hasRemaining()){
tmp[count++] = mbb.get();
}
System.out.println(new String(tmp));
fc.close();
fis.close();
}
}