Java NIO Channels

Java NIO Channels

Channels are conduits through which I/O transfers and buffers are either the sources or the targets of those data transfers. NIO Channels are like highways that efficiently transport data between byte buffers and the entity on the other end of the channel. A channel represents an open connection to an entity such as a file, a network socket, or an application that is capable of performing I/O operations such as reading or writing.

Channels are able to operate in blocking or non-blocking modes. A channel in non-blocking mode allows input/output operation without blocking the thread that invoked it. However, as of Java 1.4 only stream-oriented channels, such as sockets can be placed in non-blocking mode. Now, with the advent of Java 1.7 new classes have been added supports non-blocking or asynchronous communication like AsynchronousFileChannel.

In Java 1.7 the following channel classes are available:
AsynchronousChannelGroup, AsynchronousFileChannel, AsynchronousServerSocketChannel, AsynchronousSocketChannel, DatagramChannel, FileChannel, Pipe, SelectableChannel, ServerSocketChannel and SocketChannel

NIO Channel Properties

  • Channels can be either uni-directional or bi-directional
  • Some channels can be put into non-blocking mode (asynchronous)
  • Channels either transfer data into a buffer and pull data from a buffer

NIO Channel Interface

public interface Channel extends Closeable {
  public boolean isOpen();
  public void close() throws IOException;
}

NIO Channel Interface Hierarchy

nio_channel

Channel Operations

As you can see from above, the Channel interface has two methods which are available to all channel classes. The isOpen() method is used to see if the channel is open and the close() method is used to close an existing open channel.

Channel Implementing Classes

ClassDescription
FileChannelReads and Writes data to and from files.
DatagramChannelReads and writes data to and from the network using UDP (User Datagram Protocol) which is connectionless and does not guarantee delivery of those packets of data.
SocketChannelReads and writes data to and from the network using TCP (Transmission Control Protocol) which is reliable, ordered and guarantees delivery of data packets.
ServerSocketChannelA Java NIO ServerSocketChannel is a channel that can listen for incoming TCP connections. Server-socket channels are safe for use by multiple concurrent threads.

FileChannel

FileChannels are used for reading and writing data using file I/O. FileChannels cannot be created directly. An instance of FileChannel must be obtained by either using the getChannel() method or by calling open() method from either SocketChannel, ServerSocketChannel, DatagramChannel.

Socket and Datagram channels have open() methods allowing you to open the channel directly.

// Using ServerSocketChannel example to Open Channel
ServerSocketChannel ssc = ServerSocketChannel.open();
ServerSocket socket = ssc.socket();
socket.bind(new InetSocketAddress("localhost", 9000));

// Using SocketChannel example to Open Channel
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress("localhost", 9001));

// Using DatagramChannel example to Open Channel
DatagramChannel dc = DatagramChannel.open();
DatagramSocket ds = dc.socket();
ds.setReuseAddress(true);
ds.setBroadcast(true);
ds.bind(new InetSocketAddress(9222));

FileChannel Example

In this example, we use FileOutputStream and the getChannel() method to obtain a FileChannel.

package com.avaldes.tutorial;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.apache.log4j.Logger;

public class MyBufferWriteExample {
  private static final Logger logger
      = Logger.getLogger(MyBufferWriteExample.class);
  private static final int BUFFER_SIZE = 1024;
  private static final String FILE_NAME
      = "c:\\tmp\\output.txt";
  private static final String QUOTE
      = "If your actions inspire others to dream more, learn "
      + "more, do more and become more, you are a leader.";

  public static void main(String[] args) throws IOException {
    logger.info("Starting MyBufferWriteExample...");
    FileOutputStream fileOS = new FileOutputStream(FILE_NAME);
    FileChannel outChannel = fileOS.getChannel();

    try {
      ByteBuffer myBuffer = ByteBuffer.allocate(BUFFER_SIZE);
      myBuffer.put(QUOTE.getBytes());
      myBuffer.flip();

      int bytesWritten = outChannel.write(myBuffer);
      logger.info(
        String.format("%d bytes written to disk...", bytesWritten));
      logger.info(
        String.format("Current buffer limit=>[%d]", myBuffer.limit()));
      logger.info(
        String.format("Current buffer position=>[%d]", myBuffer.position()));
    } finally  {
      outChannel.close();
      fileOS.close();
    }
  }
}

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java_nio_channels

Java NIO Related Tutorials

  • Java NIO Tutorial
    In this tutorial series we discuss the new features of Java NIO.
  • Java NIO Buffers
    This post covers NIO Buffers in more detail and provides practical examples of using buffers in real world applications.
  • Java NIO Channels
    This post covers NIO Channels in more detail and provides examples on network connections and Java I/O in relation to files.
  • Java NIO Selectors
    In this tutorial we learn how to use the Selector class from the java.io.channels package library to build High-Performance I/O client-server using NIO.
  • Java NIO File Channel
    In this tutorial we learn how to use the FileChannel class from the java.io.channels package library and provide working examples on all of the main methods.
  • Java NIO Socket Channel
    In this tutorial we learn how to use the SocketChannel and how it is used for reading/writing stream oriented data and using TCP connection based protocol.
  • Java NIO DatagramChannel Tutorial
    In this tutorial we learn how to use the DatagramChannel to allow developers to build high-performant data streaming applications that send and receive datagrams using a protocol called UDP.
  • Java NIO and NIO2 Path Tutorial
    This tutorial will introduce the Path interface and many of its methods. The Path interface was made available as part of the Java SE 7 release in the Java NIO 2 File API.

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *