我们经常对文件进行操作,但是效率却一般。最近在研究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大小的文件。