Home » Core Java » nio » Java Nio Channels Example

About Yatin Batra

Yatin Batra
Yatin has graduated in Electronics & Telecommunication. During his studies, he has been involved with a large number of projects ranging from programming and software engineering to telecommunications analysis. He works as a software developer in the information technology sector where he is mainly involved with projects based on Java and J2EE technologies platform.

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.

Want to be a Java NIO Master ?

Subscribe to our newsletter and download the Java NIO Programming Cookbook right now!

In order to help you master Java NIO Library, we have compiled a kick-ass guide with all the major Java NIO features and use cases! Besides studying them online you may download the eBook in PDF format!

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz