Java
Summary - NIO
Combine Buffer, Channel and Selector to write an echo server.
Summary - NIO
In this group we saw the foundations of NIO: carrying data with Buffer, bidirectional IO with Channel, multiplexing with Selector, encoding with Charset, and path operations with Path/Files. These are designed for high-volume IO.
Compared to the old stream API, NIO offers block-wise and non-blocking data processing. Buffer and channel work together; selector manages many channels with one thread; charset converts between string and bytes; path and files organize file operations. Now we review with two small tasks.
Buffer and channel together
In real NIO code buffer and channel are used together. Data is first written into a buffer, then carried to a target with a channel. This is the basis of block-based data transfer.
Example: a ByteBuffer wraps a byte array, then channel.write(buffer) writes it out. The same flow works in reverse: channel.read(buffer) pulls data into the buffer, and after buffer.flip() it is read with get. This pattern repeats in file and network IO.
Exercise Print the path file name
Create a Path with Paths.get("log", "app.txt"). Print the getFileName result with System.out.println.
Show example solution
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathStringDemo {
public static void main(String[] args) {
Path p = Paths.get("log", "app.txt");
System.out.println(p.getFileName());
}
}
Exercise Print the buffer remaining count
Create a buffer with ByteBuffer.allocate(8). Write (byte) 1, (byte) 2, and (byte) 3 with put. Switch to read mode with flip. Print the remaining result with System.out.println.
Show example solution
import java.nio.ByteBuffer;
public class BufferCountDemo {
public static void main(String[] args) {
ByteBuffer b = ByteBuffer.allocate(8);
b.put((byte) 1);
b.put((byte) 2);
b.put((byte) 3);
b.flip();
System.out.println(b.remaining());
}
}
Test yourself
-
Which is used for a file path in NIO.2?
- ByteBuffer
- Selector
- Path
- Charset
Show answer
Path — A Path represents a file path.
-
Get the file name
System.out.println(p.____());
Show answer
System.out.println(p.getFileName());
Next lesson: Flow API