您的位置:首页 > 移动开发

高效的文件拷贝之MappedByteBuffer

2016-02-24 16:18 417 查看
我们经常对文件进行操作,但是效率却一般。最近在研究MappedByteBuffer的用法,下面是例子:

void MappedByteBufferTest() {
try {
RandomAccessFile source = new RandomAccessFile("F:\\cmb-flume\\flume\\logs\\relog\\paas0.log", "r");
RandomAccessFile target = new RandomAccessFile("F:\\cmb-flume\\flume\\logs\\relog\\1.log", "rw");
FileChannel in = source.getChannel();
FileChannel out = target.getChannel();
long size = in.size();
MappedByteBuffer mbbi = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
MappedByteBuffer mbbo = out.map(FileChannel.MapMode.READ_WRITE, 0, size);
long start = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
byte b = mbbi.get(i);
mbbo.put(i, b);
}
source.close();
target.close();
System.out.println("Spend: " + (System.currentTimeMillis() - start) + "ms");
} catch (Exception e) {
// TODO: handle exception
}
}打印:Spend: 170ms
paas0.log的大小是197M,耗时170毫秒,换算一下1毫秒可以读取1.15M。1秒钟的话可以读取1.13G大小的文件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: