- 分散读取指从 Channel 中读取的数据 “分散” 到多个 Buffer 中

- 聚集写入指将多个 Buffer 中的数据 “聚集” 到 Channel

public static void demo4() throws Exception {RandomAccessFile raf = new RandomAccessFile("a.txt", "rw");// 获取通道FileChannel channel = raf.getChannel();// 分配指定大小缓冲区ByteBuffer buf1 = ByteBuffer.allocate(2);ByteBuffer buf2 = ByteBuffer.allocate(1024);// 分散读取ByteBuffer[] bufs = { buf1, buf2 };channel.read(bufs); // 参数需要一个数组for (ByteBuffer byteBuffer : bufs) {byteBuffer.flip(); // 切换到读模式}System.out.println(new String(bufs[0].array(), 0, bufs[0].limit())); // 打印 heSystem.out.println(new String(bufs[1].array(), 0, bufs[1].limit())); // 打印 llo// 聚集写入RandomAccessFile raf2 = new RandomAccessFile("e.txt", "rw");// 获取通道FileChannel channel2 = raf2.getChannel();channel2.write(bufs); // 把 bufs 里面的几个缓冲区聚集到 channel2 这个通道中,聚集到通道中,也就是到了 e.txt 文件中channel2.close();}
