Definition of Java NIO Channel
Java NIO channel is nothing but the medium used to transport the data between byte buffers and entities. The java nio channel reads the data from the entity, and after reading the data it will place the same data inside into the buffers for consumption. The java nio will act as a gateway that is provided by java NIO that accesses the mechanism of IO.
Introduction to Java NIO Channel
Java nio channel contains the one-to-one relationship with the file descriptor that provides the platform independence feature. The channel represents the open connection to the specified entity of file, a network socket, and a hardware device that is capable to perform distinct IO operations like write and read. We can either open or close the channel in java nio.
The java nio channel is open as per creation, once it will be closed then this remains closed. When we have closed any channel, any attempt invokes the transaction of IO operation will cause an exception of the closed channel. The nio channel is open and tested to invoke the open method.
Key Takeaways
- As per the name, the java channel is used to flow the data from one end to another end. Java channel acts the same between the entity and buffer.
- The channel is used to read the data from the buffer. Stream is used in conventional IO channels of java.
How to Use Java NIO Channel?
The java nio channel is developed to implement the IO operations which required high speed. We have not required any custom code at the time we use the nio channel. Nio moves the time-taking activities back into the OS and increase the operational speed. The implementation of the nio channel class uses native code to perform actual work. The interface of the channel allows us to gain access to low-level services of I/O.
The below example shows how we can use the nio channel as follows. The below example shows how we can send the data from the java nio socket channel. We use a file.txt file. First, we implement the client code.
Code:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;
public class java_nio {
public static void main(String[] args) throws IOException {
ServerSocketChannel sock = null;
SocketChannel cl = null;
sock = ServerSocketChannel.open();
sock.socket().bind(new InetSocketAddress(9000));
cl = sock.accept();
System.out.println("Con Set: " + cl.getRemoteAddress());
Path p = Paths.get("G:file.txt");
FileChannel fileChannel = FileChannel.open(p,
EnumSet.of(StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE));
ByteBuffer bf = ByteBuffer.allocate(1024);
while(cl.read(bf) > 0) {
bf.flip();
fileChannel.write (bf);
bf.clear();
}
fileChannel.close();
System.out.println("Received");
cl.close();
}
}
After the creation of the client program, now in this step, we need to create a server program as follows.
Code:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
public class java_nio1 {
public static void main(String[] args) throws IOException {
SocketChannel ser = SocketChannel.open();
SocketAddress sa = new InetSocketAddress("localhost", 9000);
ser.connect(sa);
Path path = Paths.get("G:file.txt");
FileChannel fc = FileChannel.open(path);
ByteBuffer bf = ByteBuffer.allocate(1024);
while(fc.read(bf) > 0) {
bf.flip();
ser.write(bf);
bf.clear();
}
fc.close();
System.out.println ("Sent");
ser.close();
}
}
Java NIO Channel Classes
Below are the classes of the nio channel as follows. Java nio channel contains multiple classes as follows.
- AsynchronousChannelGroup – It contain a group of asynchronous channels for resource-sharing purposes.
- AsyncronousFileChannel – This is an asynchronous channel used to write, read, and manipulate files.
- Asynchronous ServerSocketChannel – This is an asynchronous channel used for the listen socket of stream-oriented.
- Asynchronous SocketChannel – This is an asynchronous channel used to connect sockets of stream-oriented.
- Channel – This is a utility method to stream and channels.
- DatagramChannel – These are selectable channels for datagram-oriented sockets.
- FileChannel – This channel is used to read and write files.
- Map mode – This is a type-safe enumeration used to map modes.
- FileLock – The token that represents the lock on the region file.
- MembershipKey – The token that represents a membership of the internet protocol.
- Pipe – It will contain pair of channels that indicates the unidirectional pipe.
- SinkChannel – The channel that represents the writable end of the file.
- SourceChannel – The channel that represents the readable end of the file.
- SelectableChannel – The channel that is multiplexed to use the selector.
- SelectionKey – The token that represents the selection.
- Selector – This will contain the multiplexor object of the selectable channel.
- SocketChannel – This is a selectable channel used to connect sockets.
- ServerSocketChannel – This is a selectable channel used to listen to sockets.
Java NIO Channel’s Primary
The nio channel of java is implemented primarily to use the below classes. The four classes used primarily in java nio channels are as follows.
- FileChannel – To read the data from the file we use the file channel class. The object of this class is created by the method of getChannel(). To use this class, we cannot create an object directly.
- DatagramChannel – This channel reads and writes the data over the network. The object of DatagramChannel is created to use the method of the factory.
- SocketChannel – This class channel reads and writes the data over the network to use TCP protocol. It uses the factory method to create an object.
- ServerSocketChannel – The ServerSocketChannel reads and writes the data on TCP connections. It will work the same as the web server. For every connection, a socket channel is created.
The below example shows the java nio channel primary as follows. We use the input file as file.txt as follows.
Code:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class java_nio {
public static void main(String[] args) throws IOException {
RandomAccessFile f = new RandomAccessFile("G:File.txt", "r");
FileChannel fc = f.getChannel();
ByteBuffer bf = ByteBuffer.allocate(512);
while (fc.read(bf) > 0) {
bf.flip();
while (bf.hasRemaining()) {
System.out.print((char) bf.get());
}
}
f.close();
}
}
Examples of Java NIO Channel
Below is an example of a java nio channel as follows. In the below example, we create a new project as follows.
1. In the first step we create a new project to use the spring tool suite. To create a new project we need to open STS as follows.
2. After open the STS, to create the new project we need to click on new and need select the maven project as follows.
3. After the selection of the maven project, we need to click on next, after a click on the next button below page will open. In that, we need to select the groupid, artifactid, and version as follows.
4. After entering the details we need to click on the finish button to create a new project with maven as follows.
5. After the creation of the project we can check the pom.xml file of the project. It will automatically create as follows.
6. Now we create a new java class into the src folder. To create a java class, we need to click on a project folder, need to select the new, and then need to select the class of the project as follows.
7. After giving the class name and click on the finish button then it will create a new class of our application as follows.
8. After the creation of the new class file we need to enter code into the newly created file as follows.
Code:
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 java_nio {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
FileInputStream ip = new FileInputStream ("G:file.txt");
ReadableByteChannel s = ip.getChannel();
FileOutputStream op = new FileOutputStream ("G:file.txt");
WritableByteChannel dest = op.getChannel();
copyData(s, dest);
System.out.println("File copied");
}
private static void copyData(ReadableByteChannel s, WritableByteChannel destination) throws IOException {
ByteBuffer bf = ByteBuffer.allocateDirect(1024);
while (s.read(bf) != -1) {
bf.flip();
while (bf.hasRemaining()) {
destination.write(bf);
}
bf.clear();
}
}
}
9. After writing the code now in this step we need to run the application and check the output of the program as follows.
Conclusion
The channel represents the open connection to the specified entity of file, a network socket, and a hardware device that is capable to perform distinct IO operations like write and read. The java nio channel reads the data from the entity, to read the data it will place the same data inside into the buffers for consumption.
Recommended Articles
This is a guide to Java NIO Channel. Here we discuss the introduction, use, java NIO channel classes and examples respectively. You can also look at the following articles to learn more –