Scatter & Gather指在多个缓冲区上实现一个简单的 I/O 操作。减少或避免了Buffer间的拷贝和系统调用。

Channel Write操作

JavaNIO - Scatter & Gather_系统调用

Write操作

Channel Read操作

JavaNIO - Scatter & Gather_系统调用_02

Read操作

public class ChannelDemo {
public static void main(String[] args) throws IOException {
ByteBuffer buffer1 = ByteBuffer.allocate(4);
ByteBuffer buffer2 = ByteBuffer.allocate(6);
ByteBuffer[] buffers = {buffer1, buffer2};

System.out.println("===Channel Read 即Scatter===");
FileInputStream fis = new FileInputStream("d:/temp/x.dat");
ScatteringByteChannel scatteringByteChannel = (ScatteringByteChannel) Channels.newChannel(fis);

scatteringByteChannel.read(buffers);//数据从Channel 散布到各个 buffers

buffer1.flip();
System.out.println(new String(buffer1.array()));
System.out.println(new String(buffer2.array()));

while (buffer1.hasRemaining()) {
System.out.println(buffer1.get());
}

buffer2.flip();
while (buffer2.hasRemaining()) {
System.out.println(buffer2.get());
}
System.out.println("===Channel Write 即Gather===");
buffer1.rewind();
buffer2.rewind();

FileOutputStream fos = new FileOutputStream("d:/temp/y.dat");
GatheringByteChannel gatheringByteChannel = (GatheringByteChannel) Channels.newChannel(fos);
buffers[0] = buffer2;
buffers[1] = buffer1;
gatheringByteChannel.write(buffers);//数据从各个 buffers 抽取到Channel
}
}

JavaNIO - Scatter & Gather_数据_03

Scatter& Gather优点

Scatter/Gather 操作会被翻译为适当的本地调用来直接填充或抽取缓冲区,减少或避免了缓冲区拷贝和系统调用

JavaNIO - Scatter & Gather_数据_04

public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}