Java NIO Channels

In Java NIO, the channel is a medium used to transports the data efficiently between the entity and byte buffers. It reads the data from an entity and places it inside buffer blocks for consumption.

Channels act as gateway provided by java NIO to access the I/O mechanism. Usually channels have one-to-one relationship with operating system file descriptor for providing the platform independence operational feature.

Let's see the class hierarchy for java.nio.channels:

Java Nio tutorial9

The above channel can be used in a blocking or a non-blocking mode, but we mainly focus on using the channel in non blocking mode.

NIO Channel Basics

Channel implementation uses the native code to perform actual work. The channel interface allows us to gain access to low-level I/O services in a portable and controlled way.

At the top of hierarchy, the Channel interface is used as given below:

As we can see in above channel interface, there are only two operations common to all the channels:

  • Checking to see if a channel is close (isclose())
  • Opening the close channel (close())

Channel Implementations

In Java NIO the primary Channels used are given below:

  • FileChannel: The file channel is used for reading the data from the files. It's object can be created only by calling the getChannel() method. We cannot create FileChannel object directly.
  • Let's see the example to create the object of FileChannel:

  • DatagramChannel: The datagram channel can read and write the data over the network via UDP (User Datagram Protocol). It uses the factory methods for creating the new object.
  • The syntax used for opening the DatagramChannel:

    The syntax used for closing the DatagramChannel:

  • SocketChannel: The datagram channel can read and write the data over the network via TCP (Transmission Control Protocol). It also uses the factory methods for creating the new object.
  • The syntax used for opening the SocketChannel:

    The syntax used for closing the SocketChannel:
  • ServerSocketChannel: The ServerSocketChannel allows user to listen the incoming TCP connections, same as a web server. For every incoming connection a SocketChannel is created.
  • The syntax used for opening the ServerSocketChannel:

    The syntax used for closing the ServerSocketChannel:


    Basic Channel Example

    Let's see the example of copy the data from one channel to another channel or from one file to another file:

    Output:

    The above program copies the content of text file testin.txt to another text file testout.txt.





Latest Courses