CodeBlanks Logo Icon CodeBlanks

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.

Practice Print the path file name

Create a Path with Paths.get("log", "app.txt"). Print the getFileName result with System.out.println.

Starter code

Main.java
// Create a path with Paths.get
// Print with getFileName

Sample solution

Main.java
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());
    }
}

Expected output

app.txt

Practice 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.

Starter code

Main.java
// Create a buffer with ByteBuffer
// Write three bytes with put
// Print remaining after flip

Sample solution

Main.java
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());
    }
}

Expected output

3

Questions and answers

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

1 Which is used for a file path in NIO.2?

  • ByteBuffer
  • Selector
  • Path Correct answer
  • Charset

Explanation: A Path represents a file path.

2 Get the file name

Question
System.out.println(p.____());
Answer
System.out.println(p.getFileName());

Explanation: getFileName returns the last path element.

All lessons in Expert