BufferedReader 和文件系统缓存

BufferedReader and File System cache

FileChannel documentation claims you can manually put file into FS cache. But FileChannel lack of any methods to read file line-by-line. In other hand BufferedReader supply you with excellent API to read file line-by-line, but BufferedReader documentation缺少关于将文件放入 FS 缓存的任何注释。

BufferedReader是否足够聪明,可以在第一次读取后将文件放入 FS 缓存?

您无法从 FileChannel 创建 BufferedReader,但您可以尝试以下操作,看看它是否能让您接近您要查找的内容:

File file = ...;
long pos = 0;
long size = file.length();
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, pos, size);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));

但是,无法保证 FileInputStream 将从映射到 MappedByteBuffer 的内存中读取。如果是这样,它可能不在不同的操作系统上。 YMMV.