Java NIO(二)- Scatter and Gather

分散(scatter)读取

        “分散读取”将数据从单个通道读取到多个缓冲区中。(数据按照缓冲区顺序依次将Buffer填满)

/*
read(ByteBuffer[] dsts)方法直接返回read(dsts, 0, dsts.length)方法;
该方法按照缓冲区在数组中出现的顺序从通道写入数据。一旦缓冲区已满,通道就会继续填充下一个缓冲区。
*/
ByteBuffer header = ByteBuffer.allocate(128); 
ByteBuffer body = ByteBuffer.allocate(1024); 
ByteBuffer[] bufferArray = { header, body }; 
channel.read(bufferArray);

 聚集(gather)写入

        “聚集写入”是将多个缓冲区的数据按照指定的顺序的依次写入单个通道中。

/*
write(ByteBuffer[] srcs)方法直接返回write(srcs, 0, srcs.length)方法;
该方法按照它们在数组中遇到的顺序写入缓冲区的内容。仅写入缓冲区的位置和限制之间的数据。
*/
ByteBuffer header = ByteBuffer.allocate(128); 
ByteBuffer body = ByteBuffer.allocate(1024); 
//将数据写入通道
ByteBuffer[] bufferArray = { header, body }; 
channel.write(bufferArray);

猜你喜欢

转载自blog.csdn.net/qq_40100414/article/details/120428902