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
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值