Java NIO Basics: Channels, Buffers, and Selectors
This article introduces Java NIO fundamentals, explaining the key concepts of Channel, Buffer, and Selector, comparing them with traditional I/O streams, and providing code examples for file reading, writing with FileChannel, and illustrating how selectors enable single‑threaded multiplexed I/O handling.
Introduction
In the previous post we discussed several I/O models; now we begin the Java NIO programming series. NIO, introduced in Java 4, provides a new API designed to overcome the limitations of traditional I/O.
Article Outline
The article is organized into four parts:
1. Basic concepts in NIO
2. Channel
3. Buffer
4. Selector
1. Basic Concepts in NIO
NIO revolves around three core concepts: Channel , Buffer , and Selector .
Channel
A Channel is analogous to a road that provides a two‑way pathway for data, unlike the one‑way streams of traditional I/O. The following code shows how traditional I/O reads a file using an InputStream:
public class Test {
public static void main(String[] args) throws IOException {
File file = new File("data.txt");
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
inputStream.read(bytes);
inputStream.close();
}
}In NIO, a Channel replaces the stream and can perform both read and write operations.
Buffer
A Buffer is a container (a continuous array) that holds data during I/O operations. All reads and writes in NIO must go through a Buffer; for example, data read from a Channel is placed into a Buffer before the application processes it.
Selector
The Selector is the most critical component of NIO. It polls registered Channels and, when an event occurs on a Channel, it retrieves the event for processing. This enables a single thread to manage multiple connections efficiently.
Below is an illustration of a Selector handling events (image omitted for brevity).
2. Channel Details
Common Channel types include:
FileChannel
SocketChannel
ServerSocketChannel
DatagramChannel
FileChannel reads from or writes to files; SocketChannel uses TCP for network I/O; ServerSocketChannel listens for incoming TCP connections and creates a new SocketChannel for each; DatagramChannel uses UDP.
The following example writes the string "java nio" to a file using a FileChannel:
public class Test {
public static void main(String[] args) throws IOException {
File file = new File("data.txt");
FileOutputStream outputStream = new FileOutputStream(file);
FileChannel channel = outputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
String string = "java nio";
buffer.put(string.getBytes());
buffer.flip(); // must flip before writing
channel.write(buffer);
channel.close();
outputStream.close();
}
}Note: The flip() call is required before invoking channel.write() to prepare the buffer for reading.
3. Buffer Details
A Buffer is an abstract class with several concrete subclasses, such as:
ByteBuffer
IntBuffer
CharBuffer
LongBuffer
DoubleBuffer
FloatBuffer
ShortBuffer
For file I/O, any of these may be used, but for network I/O the most common is ByteBuffer. Detailed usage, including the concepts of limit, position, and capacity, will be covered in a future article.
4. Selector Details
The Selector class is the core of NIO, allowing a single thread to monitor multiple Channels for events, thereby reducing system overhead and avoiding the need for a thread per connection. Each event is represented by a SelectionKey, which together with the Selector forms the essential server‑side processing logic.
Further examples of Selector usage will be presented in subsequent posts.
Reference
Original article: http://www.cnblogs.com/dolphin0520/p/3919162.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
