Blog Image

Java NIO Package  

java.nio package is provided as part of J2SE 1.4.  Previously we have package, on the top of it sun has provided java.nio package with some extended features like non-blocking and buffer oriented programming.

Stream Oriented Programming:
Java IO is a stream oriented programming where we have to read data from stream and that data cannot be cached. If we have to move back and forth in data we need to cache that data into buffer.

Buffer Oriented Programming:
Java NIO is a buffer oriented programming where once the data read then it will cached into buffer that means we dont need to cache the data by our own into buffer and we can move back and forth into the buffer.

Blocking Mode:
In I/O, the request processing will be blocked until operations like read() and write() completed. This blocking of request affects the performance of the application.

Non-Blocking Mode: 
Java NIO's non-blocking mode enables a thread to request reading currently available data. After that without waiting data to be available for reading, the thread will perform some other operation.

A container for data of a specific primitive type which can be use to write the data to the channel or to read the data from the channel. We can also say that linear, finite sequence of elements of a specific primitive type is buffer. Buffer also provides the mechanism to read the data. It also provides the tracking mechanism of data read and write. The properties of a buffer are its capacity, limit, and position:

1)Buffer Capacity:
A buffer's capacity is the number of elements it contains, that is size of the buffer. The capacity of a buffer is never negative and cannot be modified after if fixed once.

2)Buffer Limit:
A buffer's limit in write mode is the number of elements you can write in the buffer. In write mode buffer limit is equal to buffer capacity. In read mode buffer limit is many elements you can read from the buffer.

Position points to the current location of the element in buffer. On creating the buffer, position is pointing to zero. On write or read, the position is incremented to next index. Position is always set between zero and the limit of the buffer.

Channels are used for transferring data between a buffer and an entity. A channel reads data from an entity and stores it in buffer blocks for consumption. The data written into the buffer blocks can be transported by the channel to the other end.
A channel can perform both read and write. Channel can reads the data into a buffer and writes the data from a buffer. Channels can be on blocking or non-blocking modes. Data can be transferred from Channel to Channel if any one of them is a FileChannel.

The following is the example where we are storing data from file to nio buffer and then we are transfering the data from on file to other using nio channel.

public class JavaNIOTest {
    @SuppressWarnings({ "resource" })
    public static void main(String[] args) throws IOException {
        Path filePath = null;
        ByteBuffer byteBuffer = null;
        FileChannel channelRead = null;
        FileChannel targetChannel = null;

        /*Paths interface used to locate the file in file system */
        filePath = Paths.get("D:\\test.txt");

        channelRead =;
        byteBuffer = ByteBuffer.allocate(512);;
        byte[] byteArray = byteBuffer.array();
        String fileContent = new String(byteArray).trim();
        System.out.println("File Content: " + fileContent);

        targetChannel = new FileOutputStream(new File("D:\\outputChannel.txt")).getChannel();
        channelRead.transferTo(0, channelRead.size(), targetChannel);
    System.out.println("stored the data in file D:\\outputChannel.txt");

In the above program we have create 'channelRead' channel and using this channel we have read the data from the file and cached in byteBuffer. ByteBuffer.allocate(int) is for setting the capacity of the buffer.  After that we have we have transferred the data from 'channelRead' to 'targetChannel'.

The text file test.txt contains:

NIO program reading this content...

The output for the above program is:

File Content: NIO program reading this content...
stored the data in file D:\outputChannel.txt

A Selector is a Java NIO component which provides the mechanism to examine one or more NIO Channels and determines which channels are ready for data transfer i.e. for read or write operation. This way a single thread can manage multiple channels network connections.
If we are using multiple threads to handle multiple channels, it will become expensive and performance eating thing for us as we need to switch from one thread to other. Actually, we can use one thread to handle all the channels. So that we can nullify the above problems.

Selector object can be created as follows:
Selector selector =;

We can use a channel with the selector by using register method on SelectableChannel class as follows:
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);

There are four different events we can listen for, each is represented by a constant in the SelectionKey class:
  • Connect when a client attempts to connect to the server. Represented by SelectionKey.OP_CONNECT
  • Accept when the server accepts a connection from a client. Represented by SelectionKey.OP_ACCEPT
  • Read when the server is ready to read from the channel. Represented by SelectionKey.OP_READ
  • Write when the server is ready to write to the channel. Represented by SelectionKey.OP_WRITE
You can download the above program from below attachment.


About author

User Image

I am a software developer. I am working working on jdk , jee technologies. I am working on Spring Framework as well. I am passionate about learning java technologies like Web Services and Restful Services.



Be the first person to write a comment for this Blog
Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.