将文件读入OS文件缓存的最快方法

时间:2014-01-17 20:11:25

标签: java nio

我正在寻找读取文件的最快方法 - 我不需要查看读取字节,我只需要完全读取文件,以便它进入操作系统文件缓存。

这就是我目前正在使用的(但它涉及为每个文件分配一个直接缓冲区)

   FileInputStream f = new FileInputStream( file );
   FileChannel ch = f.getChannel( );
   ByteBuffer bb = ByteBuffer.allocateDirect((int)file.length() );
   ch.read(bb);

3 个答案:

答案 0 :(得分:2)

在Windows上使用/dev/nullcat,\nul将其复制到copy。无需编写任何代码。

答案 1 :(得分:1)

考虑使用内存映射文件:http://docs.oracle.com/javase/7/docs/api/java/nio/MappedByteBuffer.htmlhttp://www.codeproject.com/Tips/683614/10-Things-to-Know-about-Memory-Mapped-File-in-Java。在Unix上,你也可以在命令行中映射它们,不确定Windows。

答案 2 :(得分:-2)

感谢EJP建议,我创建了自己的/ dev / null文件通道:

   RandomAccessFile racFile = new RandomAccessFile(file, "r");
   FileChannel ch = racFile.getChannel( );
   ch.transferTo(0,  fileLength, new WritableByteChannel(){

    @Override
    public boolean isOpen() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void close() throws IOException {
        // TODO Auto-generated method stub

    }

    @Override
    public int write(ByteBuffer src) throws IOException {
        // TODO Auto-generated method stub
        int rem = src.remaining();
        return rem;
    }

   }

   );
   racFile.close();

这为我的基准测试提供了最快的解决方案。

相关问题