Java NIO ChannelsIn Java NIO, the channel is a medium used to transports the data efficiently between the entity and byte buffers. It reads the data from an entity and places it inside buffer blocks for consumption. Channels act as gateway provided by java NIO to access the I/O mechanism. Usually channels have one-to-one relationship with operating system file descriptor for providing the platform independence operational feature. Let's see the class hierarchy for java.nio.channels: The above channel can be used in a blocking or a non-blocking mode, but we mainly focus on using the channel in non blocking mode. NIO Channel BasicsChannel implementation uses the native code to perform actual work. The channel interface allows us to gain access to low-level I/O services in a portable and controlled way. At the top of hierarchy, the Channel interface is used as given below: As we can see in above channel interface, there are only two operations common to all the channels:
Channel ImplementationsIn Java NIO the primary Channels used are given below:
Let's see the example to create the object of FileChannel: The syntax used for opening the DatagramChannel: The syntax used for closing the DatagramChannel: The syntax used for opening the SocketChannel: The syntax used for closing the SocketChannel:The syntax used for opening the ServerSocketChannel: The syntax used for closing the ServerSocketChannel: Basic Channel ExampleLet's see the example of copy the data from one channel to another channel or from one file to another file: Output: The above program copies the content of text file testin.txt to another text file testout.txt. Next TopicJava NIO Buffers |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India