Lesson · File I/O
Channels, buffers and advanced I/O
14 min readChannels, Buffers & Advanced I/O
FileChannel reads and writes through ByteBuffer, transfers bytes without ever entering user space, and memory-maps files straight into the address space. The price of entry is one mental model: position, limit and flip.
ByteBuffer: one position, two modes
A ByteBuffer is capacity bytes plus a position (where the next read or write lands) and a limit (where the current view ends). Writing fills from position toward capacity; after writing you flip, which sets limit to the old position and position to zero, turning the buffer from fill mode into drain mode. Reading consumes toward the limit; compact keeps the unread tail and resumes writing after it.
Almost every NIO bug is a missing or duplicated flip: without it, a channel reads or writes a buffer whose position sits at the end, which looks like nothing happened. The second trap is one shared position pointer: a buffer cannot be read and written concurrently without care, and reused buffers need clear or rewind.
ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(42); // position 4 buffer.flip(); // limit 4, position 0: drain mode buffer.getInt(); // 42, position back at 4
FileChannel: positional and shared reads
FileChannel adds operations streams cannot express: positional reads and writes that leave the channel's own position alone (read(buffer, position)), bulk transfer between channels, locks, and force to push dirty pages to disk. Channels are thread-safe for these positional operations, which is why they appear in caches and index files.
read and write return the number of bytes transferred, which can be less than requested: the loop-until-complete pattern is part of the API contract, not an accident. On modern JDK versions the loop is often performed for you by transferTo and transferFrom.
try (FileChannel channel = FileChannel.open(path, READ, WRITE)) { channel.write(buffer, 0); // positional: does not disturb the shared position long moved = channel.transferTo(0, channel.size(), targetChannel); }
transferTo and memory mapping: skipping user space
A normal copy reads bytes into a byte array in user space and writes them back: two crossings. transferTo can hand the bytes to the kernel to move directly to the destination channel (a socket or another file), and a memory-mapped file puts the file's pages into the process address space so reads and writes become memory accesses.
Both are for genuinely large data: multi-gigabyte files, serving static assets, and random access into databases and indexes. For a config file, streams remain simpler and fast enough.
long copied = source.transferTo(0, source.size(), socketChannel); // kernel-side copy MappedByteBuffer mapped = channel.map(MapMode.READ_ONLY, 0, 4096); // pages, not buffers
Charset bridges: bytes to chars, explicitly
Channels speak bytes only, so text goes through a Charset: decode a ByteBuffer into a CharBuffer, encode back. The same rule as everywhere in I/O applies with extra force here, because these are the low-level calls where mistakes become mojibake at scale: the charset is an argument, never a default.
Decoder and Encoder objects (from charset.newDecoder()) handle partial multibyte sequences across buffer boundaries with endOfInput, which naive per-chunk decoding gets wrong. If you process UTF-8 in chunks and cut a two-byte character in half, only the stateful decoder knows how to wait for the rest.
Charset.availableCharsets(); // the alphabet of alphabets charset.newDecoder().decode(byteBuffer); // bytes -> chars, partial sequences handled charset.newEncoder().encode(charBuffer);
Buffer state · position, limit, flip
ByteBuffer.allocate(64)
allocate(64): the buffer is empty. Position and limit both sit at the start; nothing is readable or writable yet until data arrives.
Choosing the tool, bottom to top
The I/O stack is deep and every layer is right for something. The lazy decision matrix:
- Files.readString / writeString: files that comfortably fit in memory and are read whole.
- Streams (InputStream/BufferedReader): line-oriented and byte-oriented processing with plain code, any size, since memory stays bounded.
- Files.lines stream: scanning large text files line by line with pipeline-style filtering.
- FileChannel + ByteBuffer: positional access, concurrent reads, large transfers, lock coordination.
- MappedByteBuffer / transferTo: multi-gigabyte assets and kernel-side copies where user-space reads are the bottleneck.
Reach up the stack for simplicity and down only with a reason: the failure modes of channels and maps (flip discipline, page lifetime, unmapping) belong only to code that genuinely needs the performance.
One model to rule the buffers
Fill, flip, drain, compact. Every buffer API in every language is a variation of those four verbs, and every channel bug is one of them missing. Learn them once and NIO's reputation stops being scary and becomes deserved.
Interview angles
What does flip do and why is it needed?+
It sets limit to the current position and position to zero, switching a buffer from filling to draining. Without it, a channel write starts at the end of the data and transfers nothing. compact (partial drain) or clear (full reset) follow before refilling.
What advantages do FileChannels have over streams?+
Positional reads and writes without disturbing a shared position, bulk channel-to-channel transfers, file locks, force to disk, and memory mapping. Streams are simpler and often fast enough; channels are for random access and high-throughput transfers.
What is zero-copy I/O?+
transferTo/transferFrom let the kernel move bytes between a file and another channel (or socket) without staging them in user-space arrays, saving copies and context switches. It matters for large payloads.
What is a memory-mapped file used for?+
Random access into very large files (indexes, databases, multimedia) where the OS page cache serves reads and dirty pages are written back by the kernel. Benefits come with constraints: page-granular locking, file-size stability and subtle unmapping rules.
Why do chunked UTF-8 reads need a stateful decoder?+
A multibyte sequence can be split across chunks. CharsetDecoder keeps partial-sequence state and only completes a character when the remaining bytes arrive; decoding each chunk independently would corrupt boundary characters.