Java NIO 02 === Channel
The Java NIO channel is similar to a stream, but it is somewhat different:
- Data can be read from the channel and written to the channel. However, stream read/write is usually unidirectional.
- The channel can be read and written asynchronously.
- The data in the channel always needs to read a Buffer first, or always needs to be written from a Buffer.
As mentioned above, data is read from the channel to the buffer zone, and data is written from the buffer zone to the channel. As shown in:
Channel implementation
These are the most important channel implementations in Java NIO:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
FileChannel reads and writes data from a file.
Mongoramchannel can read and write data in the network through UDP.
SocketChannel can read and write data in the network through TCP.
The ServerSocketChannel can listen to new TCP connections, just like the Web server. A SocketChannel is created for each new connection.
Basic Channel example
The following is an example of using FileChannel to read data to the Buffer:
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } aFile.close();
Help
Pay attention to the call of buf. flip (). First, read the data to the Buffer, then reverse the Buffer, and then read the data from the Buffer. The next section will explain more details about the Buffer.