Java
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.
Exercise 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()).
Show example solution
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());
}
}
}
Test yourself
-
Complete the ByteBuffer creation
ByteBuffer buf = ByteBuffer.____(16);
Show answer
ByteBuffer buf = ByteBuffer.allocate(16);
-
How is a file opened with FileChannel?
- new FileChannel()
- Files.openChannel(path)
- FileChannel.open(path, option)
- channel.of(path)
Show answer
FileChannel.open(path, option) — FileChannel.open(path, option) opens it.
-
Match Channel concepts
- FileChannel
- File channel
- ByteBuffer
- Data buffer
- flip()
- Prepares for reading
- StandardOpenOption
- Open options
Next lesson: Summary - I/O and NIO basics