首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > Access >

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

2012-08-26 
通过扩展RandomAccessFile类使之具备Buffer改善I/O性能转自http://www.bianceng.cn/Programming/Java/2011

通过扩展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兆的文件,(这里牵 涉到读和写):

读写耗用时间(秒)RandomAccessFileRandomAccessFile95.848BufferedInputStream + DataInputStreamBufferedOutputStream + DataOutputStream2.935BufferedRandomAccessFileBufferedOutputStream + DataOutputStream2.813BufferedRandomAccessFileBufferedRandomAccessFile2.453BufferedRandomAccessFile优BufferedRandomAccessFile优2.197BufferedRandomAccessFile完BufferedRandomAccessFile完0.401MappedByteBuffer+ RandomAccessFileMappedByteBuffer+ RandomAccessFile1.209

确实不错,看来JDK1.4比1.3有了极大的进步。如果以后采用1.4版本开发软 件时,需要对文件进行随机访问,建议采用 MappedByteBuffer+RandomAccessFile的方式。但鉴于目前采用JDK1.3及以前的 版本开发的程序占绝大多数的实际情况,如果您开发的JAVA程序使用了 RandomAccessFile类来随机访问文件,并因其性能不佳,而担心遭用户诟病,请 试用本文所提供的BufferedRandomAccessFile类,不必推翻重写,只需IMPORT 本类,把所有的RandomAccessFile改为BufferedRandomAccessFile,您的程序的 性能将得到极大的提升,您所要做的就这么简单。

未来的考虑

读者可在此基础上建立多页缓存及缓存淘汰机制,以应付对随机访问强度大 的应用。

热点排行