Video in progress

Strong Middle 📁 IO and NIO

You need to read one record from the middle of a multi-gigabyte file. How do you do it, and why is a stream awkward here?

With FileChannel (or the old RandomAccessFile) you do a positional read from an exact offset: channel.read(buf, offset). An InputStream only moves sequentially, and skip has no guarantees and is slow in many cases.

📖 Answer

Suppose the file consists of fixed-length records, each 128 bytes. The offset of the 10-millionth record is 10_000_000L * 128. With a stream, you would have to read through and throw away 1.2 GB to get there.

try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) {
    ByteBuffer rec = ByteBuffer.allocate(128);
    long offset = index * 128L;          // long! it overflows with int
    while (rec.hasRemaining()) {
        if (ch.read(rec, offset + rec.position()) < 0) throw new EOFException();
    }
    rec.flip();
    return Record.decode(rec);
}

read(ByteBuffer, long position) does not change the channel's current position. That is why a single FileChannel can be read by several threads at once from different places. This is a big advantage over the RandomAccessFile.seek() + read() pair, where another thread can move the position between the seek and the read.

Computing the offset with an int is a classic bug: past 2 GB you get a negative number. Always use long.

If the records have variable length, you keep a separate index file (record number → offset); many databases and Kafka segments are built this way.