CodeBlanks Logo Icon CodeBlanks

Channels

Learn channel-based I/O with FileChannel.

Channels

Channel is the core NIO interface; FileChannel is used for file operations. Data is buffered into a ByteBuffer and read from or written to the channel.

try (FileChannel ch = FileChannel.open(p,
        StandardOpenOption.READ)) {
    ByteBuffer buf = ByteBuffer.allocate(16);
    ch.read(buf);
    buf.flip();
}

Here flip() prepares the buffer for reading. Unlike streams, channels can move back and forth. This enables efficient access for large files. This is the foundation of the modern NIO API.

flip and rewind

buf.flip() prepares the buffer for reading: it resets the position and updates the limit. rewind() resets the position but leaves the limit unchanged.

buf.put((byte) 65);  // 'A'
buf.flip();
byte b = buf.get();  // 65

This is a standard pattern in read/write transitions. clear() prepares the buffer for writing again. These methods appear often in NIO code; correct use is critical for performance and correctness.

Practice Read a byte with FileChannel

Write main in a ChannelDemo class; create a temp file with Files.createTempFile("c", ".txt"), write Files.writeString(p, "AB"). In a try (FileChannel ch = FileChannel.open(p, StandardOpenOption.READ)) block, create ByteBuffer buf = ByteBuffer.allocate(2), call ch.read(buf), buf.flip() and print the first character with System.out.println((char) buf.get()).

Starter code

Main.java
import java.nio.file.*;
import java.nio.channels.*;
import java.nio.*;

// Write main in ChannelDemo

// Set up with createTempFile and writeString; open FileChannel; read+flip+get and print first char

Sample solution

Main.java
import java.nio.file.*;
import java.nio.channels.*;
import java.nio.*;

class ChannelDemo {
    public static void main(String[] args) throws Exception {
        Path p = Files.createTempFile("c", ".txt");
        Files.writeString(p, "AB");
        try (FileChannel ch = FileChannel.open(p, StandardOpenOption.READ)) {
            ByteBuffer buf = ByteBuffer.allocate(2);
            ch.read(buf);
            buf.flip();
            System.out.println((char) buf.get());
        }
    }
}

Expected output

A

Questions and answers

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

1 Complete the ByteBuffer creation

Question
ByteBuffer buf = ByteBuffer.____(16);
Answer
ByteBuffer buf = ByteBuffer.allocate(16);

Explanation: ByteBuffer.allocate(n) creates a buffer.

2 How is a file opened with FileChannel?

  • new FileChannel()
  • Files.openChannel(path)
  • FileChannel.open(path, option) Correct answer
  • channel.of(path)

Explanation: FileChannel.open(path, option) opens it.

3 Match Channel concepts

Term Meaning
FileChannel File channel
ByteBuffer Data buffer
flip() Prepares for reading
StandardOpenOption Open options

All lessons in Advanced