Channel introduction

All NIO operations begin with a Channel, which is a source of data or a destination where data is written. Primarily, the java.niO package implements the following channels:

FileChannel: FileChannel for reading and writing files

DatagramChannel: Used for receiving and sending UDP connections

SocketChannel: a TCP connection channel or TCP client

ServerSocketChannel: TCP server that listens for incoming requests from a certain port

The idea of a channel is that reading a channel is reading data from a channel into a buffer,

Channel writing is writing data from a buffer to a channel,

Make sure you understand the order. A channel can be understood as a connection and is bidirectional, readable and writable. Network channels will be demonstrated later. Here is a file channel.

FileChannel -FileChannel

Let’s look at a file copy example, first define the source file to copy and the destination of the copy:

The destination has no content:

Then read the file into the stream and get the channel from the stream:

Now that we have channels, we need buffers for both reading and writing.

Let’s start the copy operation:

Program logic is relatively simple, each time read 1024, read from the source file, write to the target directory file, read the exit, pay attention to the middle read and write mode conversion. Note that at the beginning, for the fromFileChannel it was a read, reading from the channel into buffer, and for buffer it was a write, writing from the fromFileChannel to buffer.

The subsequent copy is a write operation for the toFileChannel, where the data is written from the buffer to the channel of the target file. In the case of buffer, this is a read operation, and the data in the buffer is read.

As you can see from the above, buffer is a two-channel buffer that lives up to its name.

The code address: https://gitee.com/blueses/netty-demo 03

This article is published by OpenWrite!