Channel (channel) Introduction
All operations begin NIO channel, the data channel is the destination or source of data writing, the following mainly Channel, the java.nio package Main achieved:
FileChannel: file path, the file for read and write
DatagramChannel: means for receiving and sending the UDP connection
SocketChannel: I understand it as a TCP connection channel, simple to understand TCP client
ServerSocketChannel: TCP corresponding server, listening on a port for incoming requests
Channel concept needs to know is that the channel is to read data from the read channel buffer inside,
Channel write data from the buffer is to be written in the channel,
This order must be clear. In fact, the channel can be understood as a connector, and the channel is bidirectional, readable and writable. Behind network channel will be dedicated to the presentation, following a presentation file channel.
File channel -FileChannel
Let's look at an example of a copy of a file, first define the copy source file and the copy destination:
This time the destination is not content:
Then read the file to a stream, then the acquisition channel stream:
With the channel later, whether read or write buffer is required to create a buffer zone the following:
Copying operation starts following:
Program logic is simple, each read 1024, read from the source file into the target directory files, read the exit, pay attention to convert the intermediate read-write mode. Note that the start time for fromFileChannel read operation is read from the channel to the buffer, the buffer at this time is for a write operation, data is written from fromFileChannel buffer.
While the back of the copy is for toFileChannel write operation, data is written from the channel buffer of the object file. For the buffer at a time is read, the data buffer is read.
As can be seen from the above buffer as a buffer between the two channels is truly.
Code address: https: //gitee.com/blueses/netty-demo 03
This article from the blog article multiple platforms OpenWrite release!