Scatter & Gather指在多个缓冲区上实现一个简单的 I/O 操作。减少或避免了Buffer间的拷贝和系统调用。
Channel Write操作
|
---|
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a1b18566bdb169c863987a08c85f4126.png) |
Write操作 |
Channel Read操作
|
---|
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9ff89c45ce8373110b49f47c97c6fed9.png) |
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);
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);
}
}
|
---|
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d6d72e05705a754937eb94a3a12ddb1c.png) |
Scatter& Gather优点
Scatter/Gather 操作会被翻译为适当的本地调用来直接填充或抽取缓冲区,减少或避免了缓冲区拷贝和系统调用
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}