I am looking for the fastest way of reading a file - I don't need to see the read bytes, I just need the file to be fully read so that it gets in the OS file cache.
This is what I am using at the moment (but it involves allocating a direct buffer for each file)
FileInputStream f = new FileInputStream( file );
FileChannel ch = f.getChannel( );
ByteBuffer bb = ByteBuffer.allocateDirect((int)file.length() );
ch.read(bb);
Thanks to EJPs suggestion, I created my own /dev/null file channel:
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();
This provided the fastest solution in my benchmarks.