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

通过扩展RandomAccessFile类使之具备Buffer改善I/O性能

转自http://www.bianceng.cn/Programming/Java/201106/27186.htm

?

过程有点长。

略。。。。。。。。。。。。。。

?

与JDK1.4新类MappedByteBuffer+RandomAccessFile的对比?

JDK1.4提供了NIO类 ,其中MappedByteBuffer类用于映射缓冲,也可以映射 随机文件访问,可见JAVA设计者也看到了RandomAccessFile的问题,并加以改进 。怎么通过MappedByteBuffer+RandomAccessFile拷贝文件呢?下面就是测试程 序的主要部分:

RandomAccessFile rafi = new RandomAccessFile(SrcFile, "r");
  RandomAccessFile rafo = new RandomAccessFile(DesFile, "rw");
  FileChannel fci = rafi.getChannel();
FileChannel fco = rafo.getChannel();
  long size = fci.size();
  MappedByteBuffer mbbi = fci.map(FileChannel.MapMode.READ_ONLY, 0, size);
MappedByteBuffer mbbo = fco.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);
}
fcin.close();
fcout.close();
rafi.close();
rafo.close();
System.out.println("Spend: "+(double) (System.currentTimeMillis()-start) / 1000 + "s");

试一下JDK1.4的映射缓冲读/写功能,逐字节COPY一个12兆的文件,(这里牵 涉到读和写):

耗用时间(秒)
RandomAccessFile RandomAccessFile