分散(Scatter)与聚集(Gather)

分散读取(Scattering Reads) : 将通道中的数据分散到多个缓冲区中

聚集写入(Gathering Writes) : 将多个缓冲区中的数据聚集到通道中

//分散和聚集
@Test
public void test4() throws IOException{
    RandomAccessFile raf1 = new RandomAccessFile("a.txt", "rw");

    //1. 获取通道
    FileChannel channel = raf1.getChannel();

    //2. 分配指定大小的缓冲区
    ByteBuffer buf1 = ByteBuffer.allocate(100);
    ByteBuffer buf2 = ByteBuffer.allocate(1024);

    //3. 分散读取
    ByteBuffer[] buffers = {buf1,buf2};
    channel.read(buffers);

    for (ByteBuffer buffer : buffers) {
        buffer.flip();
    }
    System.out.println(new String(buffers[0].array(),0,buffers[0].limit()));
    System.out.println("===============================");
    System.out.println(new String(buffers[1].array(),0,buffers[1].limit()));

    //4. 聚集写入
    RandomAccessFile raf2 = new RandomAccessFile("juji.txt", "rw");
    FileChannel channel2 = raf2.getChannel();
    channel2.write(buffers);
}