Home » Java NIO Components

Java NIO Components

by Online Tutorials Library

Java NIO Components

In Java NIO reading and writing are the fundamental process of I/O. Reading from channel: We can create a buffer and then ask a channel to read the data. Writing from channel: We can create a buffer, fill it with data and ask a channel to write the data.

The core components used in the reading and writing operation are:

  • Channels
  • Buffers
  • Selectors

Java NIO has more components and classes than these, but the Channel, Buffer and Selector uses as the core of the API.

Channels and Buffers

In standard I/O API the character streams and byte streams are used. In NIO we work with channels and buffers. All the I/O in NIO is started with a channel. Data is always written from a buffer to a channel and read from a channel to a buffer.

Data reading operation:

Let’s see the channels read data into buffers illustration shown below:

Java Nio tutorial2

Data writing operation:

Let’s see the buffers write data into channels illustration shown below:

Java Nio tutorial3

Channels List

In Java NIO the primary Channels used are given below:

  • DatagramChannel
  • SocketChannel
  • FileChannel
  • ServerSocketChannel

The above channels cover the UDP (User Datagram Protocol)+TCP(Transmission Control Protocol) network I/O, and file I/O.

Buffers List

In Java NIO the core Buffer used are given below:

  • CharBuffer
  • DoubleBuffer
  • IntBuffer
  • LongBuffer
  • ByteBuffer
  • ShortBuffer
  • FloatBuffer

The above buffer’s cover the basic data types that we can send via I/O: characters, double, int, long, byte, short and float.


Selectors

Java NIO provides the concept of “selectors”. It is an object that can be used for monitoring the multiple channels for events like data arrived, connection opened etc. Therefore single thread can monitor the multiple channels for data.

It is used if the application has many Channels (connections) open, but has low traffic on each connection. For example: In a chat server.

Let’s see the thread using a Selector to handle the 3 Channel’s illustration shown below:

Java Nio tutorial4

Next TopicJava NIO Package

You may also like