日期:2014-05-16  浏览次数:20394 次

Java的内存映射--MappedByteBuffer
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;


public class MapFileDemo {

/**
*    对于大多数操作系统而言,与通过普通的 read 和 write 方法读取或写入数千字节的数据相比,
*    将文件映射到内存中开销更大。从性能的观点来看,通常将相对较大的文件映射到内存中才是
*    值得的,但是不是越大越好,在超过了相对了内存大小的一定比例之后会抛出异常。
     *    MappedByteBuffer直接字节缓冲区,其内容是文件的内存映射区域。映射的字节缓冲区是通过
     *     FileChannel.map 方法创建的.
*/
public static void main(String[] args) throws FileNotFoundException,IOException {
       
MappedByteBuffer mapFile = new RandomAccessFile("D://text.txt", "rw")
       .getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 1000000);


Long startTime = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++ ){
mapFile.put((byte)('i'+i));
}
System.out.println("Memory reflect finish!");
for(int i = 0; i < 1000000; i++){
mapFile.get(i);
}
Long endTime = System.currentTimeMillis();
        System.out.println("the spend time is: " + (endTime-startTime));
       
使用内存映射的方式进行读写所消耗的时间是:  the spend time is: 31


// RandomAccessFile rf = new RandomAccessFile("D://text1.txt", "rw");
// Long startTime = System.currentTimeMillis();
// for(int i = 0; i < 1000000; i++ )
// rf.write('i'+i);
//
// for(int j = 0; j < 1000000; j++ ){
// rf.read();
//
// }
//
// Long endTime = System.currentTimeMillis();
// System.out.println("the spend time is: " + (endTime-startTime));
使用RandomAccessFile操作消耗的时间:the spend time is: 7956


        File file = new File("D://t1.txt");
        FileInputStream fi = new FileInputStream(file);
        FileOutputStream fo = new FileOutputStream(file);
        Long startTime = System.currentTimeMillis();
        for(int i = 0; i < 1000000; i++ ){
        fo.write((byte)('b'+i));
}
        for(int i = 0; i < 1000000; i++){
fi.read();
}
Long endTime = System.currentTimeMillis();
        System.out.println("the spend time is: " + (endTime-startTime));
使用普通的IO操作消耗的时间是:the spend time is: 8093
}

}