Java-Channels

Channels

Channels are defined in java.nio.channels. Channels are analogous to streams in the original I/O package. A channel represents an open connection to an Input/Output device, such as a file or a socket. All data that goes anywhere (or comes from anywhere) must pass through a Channel object. In general, to use the NIO system, you obtain a channel to an Input/Output device and a buffer to hold data. You then operate on the buffer, inputting or outputting data as needed.

All channels are instances of classes that ultimately implement the java.nio.channels.Channel interface. Channel declares the following methods :

Method Description
void close() Close this channel. When this channel is already closed, invoking close() has no effect. When another thread has already invoked close(), a new close() invocation blocks until the first invocation finishes, after which close() returns without effect. This method throws java.io.IOException when an I/O error occurs.
boolean isOpen() Return this channel’s open status. This method returns true when the channel is open; otherwise, it returns false.

These methods indicate that only two operations are common to all channels: close the channel and determine whether the channel is open or closed.

WritableByteChannel and ReadableByteChannel

To support I/O, Channel is extended by the WritableByteChannel and ReadableByteChannel interfaces :

channels

Interface Description
WritableByteChannel WritableByteChannel declares an abstract int write(ByteBuffer buffer) method that writes a sequence of bytes from buffer to the current channel. This method returns the number of bytes actually written. It throws java.nio.channels.NonWritableChannelException when the channel was not opened for writing, and IOException when some other I/O error occurs.
ReadableByteChannel ReadableByteChannel declares an abstract int read(ByteBuffer buffer) method that reads bytes from the current channel into buffer. This method returns the number of bytes actually read (or -1 when there are no more bytes to read). It throws java.nio.channels.NonReadableChannelException when the channel was not opened for reading, and IOException when some other I/O error occurs.

A channel whose class implements only WritableByteChannel or ReadableByteChannel is unidirectional. Attempting to read from a writable byte channel or write to a readable byte channel results in a thrown exception.

Obtaining a Channel

In general, to use the NIO system, you obtain a channel to an Input/Output device and a buffer to hold data. You then operate on the buffer, inputting or outputting data as needed. There are two ways to obtain a channel.

Method One

The java.nio.channels package provides a Channels utility class that offers two methods for obtaining channels from streams. For each of the following methods, the underlying stream is closed when the channel is closed, and the channel isn’t buffered :

Method Description
WritableByteChannel newChannel(OutputStream outputStream) Returns a writable byte channel for the given OutputStream.
ReadableByteChannel newChannel(InputStream inputStream) Returns a readable byte channel for the given InputStream.

Method Two

Various classic I/O classes have been retrofitted to support channel creation. For example, java.io.RandomAccessFile declares a FileChannel getChannel() method for returning a file channel, and java.net.Socket declares a SocketChannel getChannel() method for returning a socket channel.

Closing Channel

When you are done with a channel, you must close it. This is done by calling the close( ) method. All channels implement AutoCloseable, you can use a try-with-resources statement to close the file automatically instead of calling close( ) explicitly. The following program uses the Channels class to obtain channels for the FileInputStream and FileOutputStream and then uses these channels to copy bytes from the input channel to the output channel. Finally, both channels are closed.

Program

Java Channels


Program Source

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

public class Javaapp {

    public static void main(String[] args) throws IOException {
        
        FileInputStream fi = new FileInputStream("data1.txt");
        ReadableByteChannel src = Channels.newChannel(fi);
        FileOutputStream fo = new FileOutputStream("data2.txt");
        WritableByteChannel dest = Channels.newChannel(fo);
        
        ByteBuffer buf = ByteBuffer.allocate(6);
        
        while (src.read(buf) != -1)
        {
            buf.flip();
            dest.write(buf);
            buf.clear();
        }
        src.close();
        dest.close();
    }
}

Leave a Comment