Video in progress

What is an NIO Channel, and how does it differ from the classic InputStream/OutputStream?

A Channel is two-way communication with a file or socket: you can both read from and write to the same object, and it works through a ByteBuffer. A stream is one-directional and blocking; a channel can be switched to non-blocking mode and used with a Selector.

📖 Answer

The main differences:

Stream Channel
Direction read only or write only both (FileChannel, SocketChannel)
Unit of data byte / array ByteBuffer
Non-blocking no yes, on socket channels
Changing position no (only skip) anywhere with position(long)

FileChannel gives you capabilities streams don't have:

try (FileChannel ch = FileChannel.open(path, StandardOpenOption.READ)) {
    ByteBuffer buf = ByteBuffer.allocate(4096);
    ch.read(buf, 1_000_000);   // read from exactly the 1 MB position
}

Also: transferTo (zero-copy transfer), map (memory-mapped file), lock (file lock), force (forced write to disk).

For files, FileChannel is always blocking: non-blocking exists only on network channels. For ordinary file reads and writes, channels are not noticeably faster than streams; they pay off when you need the special capabilities.