nio

Java Nio Channels Example

Channels are the second major innovation of the Java Nio after buffers. In Java Nio, channels are used for the input-output transfers and this tutorial explains how the Java Nio Channels are used to open the network connections and connections to the files.
 
 
 
 
 
 
 
 

1. Introduction

Java Nio was developed to allow the Java programmers implement the high-speed I/O operations without using the custom native code. Nio moves the time-taking I/O activities like filling, namely and draining buffers etc back into the operating system, thus allows an increase in the operational speed.

Java Nio consists of the following core components:

  • Channel & Buffers: In standard, I/O API the character streams and the byte streams are used but in NIO, developers work with the channels and buffers. In this case, the data is always written from a buffer to a channel and read from a channel to a buffer

    Fig. 1: Channel & Buffers
    Fig. 1: Channel & Buffers
  • Selectors: It is an object that can be used for monitoring the multiple channels for events like data arrived, connections opened etc. Thus, a single thread can monitor the multiple channels for the data

    Fig. 2: A Thread uses a Selector to handle 3 Channel's
    Fig. 2: A Thread uses a Selector to handle 3 Channel’s
  • Non-blocking I/O: Here the application immediately returns the available data and application should have a pooling mechanism to find out when more data is available

Do note, Java NIO has more components and classes but the Channel, Buffer, and Selector are used as the core of the API.

1.1 Java Nio Components

The Java Nio classes are contained in the java.nio package and it is important to understand that the Nio subsystem does not replace the existing stream-based I/O classes available in java.io package. The important Nio classes are grouped under different categories that are shown below:

Fig. 3: Nio Components
Fig. 3: Nio Components

Let us understand the important classes contained in these groups.

PackagePurpose
java.nioIt is a top-level package for NIO system. The various types of buffers are encapsulated by this NIO system.
java.nio.charsetIt encapsulates the character sets and also supports the encoding and the decoding operation that converts the characters to bytes and bytes to characters.
java.nio.charset.spiIt supports the service provider for the character sets.
java.nio.channelsIt supports the channel which is essentially open for the I/O connections.
java.nio.channels.spiIt supports the service providers for the channels.
java.nio.fileIt provides the support for the files.
java.nio.file.spiIt supports the service providers for the file system.
java.nio.file.attributeIt provides the support for the file attributes.

1.2 Java Nio Channels

In Java Nio, Channels are used for the input-output transfers. A channel is a like a tube that transports the data between a buffer and an entity at the other end. A channel reads the data from an entity and places it in the buffer blocks for consumption. The developers then write the data to the buffer blocks so that it can be transported by the channel to the other end.

Channels are the gateway provided by the Java Nio package to access the native input-output mechanism. Developers should use buffers to interact with the channels and to perform the input-output operations where these buffers act as the endpoints provided by the channels to send and receive the data.

Fig. 4: Class hierarchy for Java Nio Channels
Fig. 4: Class hierarchy for Java Nio Channels

1.2.1 Channel Characteristics

  • Unlike streams, channels are two-way in nature and can perform both, read and write operations
  • A channel reads the data into a buffer and writes the data from a buffer
  • A channel can even perform the asynchronous read and write operations
  • A non-blocking channel does not put the invoking thread in the sleep mode
  • Stream-oriented channels like sockets can only be placed in the non-blocking mode
  • The data can be transferred from one channel to another if any one of the channels is a FileChannel

Fig. 5: NIO Channels
Fig. 5: NIO Channels

1.2.2 Channel Classes

Below are the two major types of channel classes provided as an implementation in the Java Nio package:

  • FileChannel: These are the File-based read/write channels that cannot be placed in a non-blocking mode
  • SocketChannel: The Java Nio Socket Channel is used for connecting a channel with a TCP network socket. It is equivalent to the Java Networking Sockets used in the network programming. There are two methods available in the Java Nio package for creating a SocketChannel i.e. ServerSocketChannel and the DatagramChannel. Do note, SocketChannel are the selectable channels that can easily operate in the non-blocking mode

Now, open up the Eclipse IDE and let’s see the basics of the Java Nio Channel.

2. Java Nio Channel Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 6: Java Nio Channel Project Structure
Fig. 6: Java Nio Channel Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 7: Create Maven Project
Fig. 7: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 8: Project Details
Fig. 8: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 9: Archetype Parameters
Fig. 9: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaNioChannel</groupId>
	<artifactId>JavaNioChannel</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want like JUnit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 10: Java Package Creation
Fig. 10: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.nio.

Fig. 11: Java Package Name (com.jcg.java.nio)
Fig. 11: Java Package Name (com.jcg.java.nio)

Once the package is created in the application, we will need to create the implementation class. Right-click on the newly created package: New -> Class.

Fig. 12: Java Class Creation
Fig. 12: Java Class Creation

A new pop window will open and enter the file name as: ChannelExample. The receiver class will be created inside the package: com.jcg.java.nio.

Fig. 13: Java Class (ChannelExample.java)
Fig. 13: Java Class (ChannelExample.java)

3.1.1 Implementation of Utility Class

Let’s see the example of copying the data from one channel to another channel (or from one file to another file). Add the following code to it:

ChannelExample.java

package com.jcg.java.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class ChannelExample {

	@SuppressWarnings("resource")
	public static void main(String[] args) throws IOException {

		// Path Of The Input Text File
		FileInputStream input = new FileInputStream ("config/sampleInput.txt");
		ReadableByteChannel source = input.getChannel();  

		// Path Of The Output Text File
		FileOutputStream output = new FileOutputStream ("config/sampleOutput.txt");
		WritableByteChannel destination = output.getChannel();  
		copyData(source, destination);
		System.out.println("! File Successfully Copied From Source To Desitnation !");
	}

	private static void copyData(ReadableByteChannel source, WritableByteChannel destination) throws IOException {
		ByteBuffer buffer = ByteBuffer.allocateDirect(1024);  
		while (source.read(buffer) != -1) {  
			// The Buffer Is Used To Be Drained
			buffer.flip();  

			// Make Sure That The Buffer Was Fully Drained  
			while (buffer.hasRemaining()) {  
				destination.write(buffer);  
			}

			// Now The Buffer Is Empty!
			buffer.clear();
		} 
	}
}

4. Run the Application

To run the Java Nio application, Right-click on the ChannelExample class -> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 14: Run Application
Fig. 14: Run Application

5. Project Demo

When developers run the above program, the input file’s data will be copied to the output’s file and the code shows the following status as output.

Fig. 15: Output File
Fig. 15: Output File

That’s all for this post. Happy Learning!!

6. Conclusion

This tutorial uses a simple example to illustrate the Channel’s functionality and helps developers understand the basic configuration required to achieve this operation. That’s all for this tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Java Nio for the beginners.

Download
You can download the full source code of this example here: JavaNioChannel

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button