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

本文介绍了Java NIO中分散(Scatter)和聚集(Gather)的概念及其实现方式。分散是指从通道读取数据到多个缓冲区,而聚集则是指将多个缓冲区的数据写入到通道中。通过具体的代码示例展示了如何使用这两种机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于通道,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个缓冲区,也就是第二个,第三个和第四个缓冲区。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值