Java NIO 通道(二)通道分散/聚集

基于通道,NIO又提供了另一个重要功能,分散(Scatter)和聚集(Gather)。

Scatter(分散):指的是从通道中读取(read)数据分散到多个缓冲区Buffer中,该过程会将每个缓冲区填满,直到通道中无数据或者缓冲区没有空间。

Gather(聚集):指的是将多个缓冲区Buffer聚集起来写入(write)通道的过程,类似于将多个缓冲区的内容链接起来写入通道。

代码

public interface ScatteringByteChannel extends ReadableByteChannel {
    public long read(ByteBuffer[] dsts, int offset, int length) throws IOException;

    public long read(ByteBuffer[] dsts) throws IOException;

}

public interface GatheringByteChannel extends WritableByteChannel {

    public long write(ByteBuffer[] srcs, int offset, int length) throws IOException;

    public long write(ByteBuffer[] srcs) throws IOException;

}

1. 分散和聚集都是以缓冲区为入参

2. offset和length参数是read和write方法可以使用的缓冲区的子集,它不是一个简单的位移和长度,而是指的是缓冲区数组的索引和需要使用的缓冲区数量。

Gather写入

        ByteBuffer header = ByteBuffer.allocate(10);
        ByteBuffer body   = ByteBuffer.allocate(40);

        ByteBuffer[] bufferArray = { header, body };

        channel.write(bufferArray);

写入时会将header和body内的数据写入到通道。写入时需要根据position和limit的位置来写入header和body中的数据。


Scatter读取

        ByteBuffer header = ByteBuffer.allocate(10);
        ByteBuffer body   = ByteBuffer.allocate(40);

        ByteBuffer[] bufferArray = { header, body };

        channel.read(bufferArray);
读取时会将通道的数据写入到Buffer中,当一个Buffer满了之后,会写入到另一个Buffer中。假设通道中有48个字节,那么10个字节写入到header中,剩下的38字节写入body中。


offset和length的Scatter读取和Gather写入

int bytesRead = channel.write (fiveBuffers, 1, 3);

fiveBuffers有5个Buffer数组,参数1和3代表了将使用下标是1开始的3个缓冲区,也就是第二个,第三个和第四个缓冲区。

猜你喜欢

转载自blog.csdn.net/qq_32924343/article/details/80605239
今日推荐