CodeBlanks Logo Icon CodeBlanks

Channel

Learn the NIO channel with Channel.

The Channel concept

A Channel carries data through a buffer. Unlike streams, a channel can be bidirectional and switch to non-blocking mode. This is more efficient for high-volume IO.

Example: a WritableByteChannel takes a ByteBuffer and writes it to a target with write. With Channels.newChannel(out) an ordinary OutputStream is wrapped as a channel. So stream-based code can work with the NIO channel API. Channels are closed with close.

Channel versus stream

Streams work with single bytes or byte arrays; a channel moves data in blocks through a ByteBuffer. Streams are usually blocking; some channel types can switch to non-blocking mode.

Example: FileChannel opens a channel to a file directly; read and write take a buffer. This is faster than a stream for large files. Methods like transferTo copy data directly from channel to channel. So channels are preferred in high-performance IO.

Practice Write bytes to a channel

Create a ByteArrayOutputStream out. Wrap the channel with WritableByteChannel ch = Channels.newChannel(out). Prepare a two-byte buffer with ByteBuffer.wrap(new byte[]{65, 66}). Write with ch.write(b), close with ch.close(). Print the result of new String(out.toByteArray()) with System.out.println.

Starter code

Main.java
// Create a ByteArrayOutputStream
// Wrap the channel with Channels.newChannel
// Write and print the result

Sample solution

Main.java
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;

public class ChannelDemo {
    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        WritableByteChannel ch = Channels.newChannel(out);
        ByteBuffer b = ByteBuffer.wrap(new byte[]{65, 66});
        ch.write(b);
        ch.close();
        System.out.println(new String(out.toByteArray()));
    }
}

Expected output

AB

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Channel concepts

Term Meaning
Channel Data channel
ByteBuffer Carried data
write Writes a buffer
Channels.newChannel Stream to channel

2 What kind of data does a Channel work with?

  • Strings
  • Characters
  • ByteBuffer Correct answer
  • Objects

Explanation: A Channel carries data through a ByteBuffer.

3 Complete the Channels.newChannel call

Question
WritableByteChannel ch = Channels.____(out);
Answer
WritableByteChannel ch = Channels.newChannel(out);

Explanation: newChannel wraps a stream as a channel.

All lessons in Expert