Java NIO的Scatter与Gather

Scatter(分散):分散读取,从管道Channel中读取的数据分散到一个或者多个缓冲区Buffer中,分散的时候会依次的按缓冲区的顺序一个一个的进行。
Gather(聚集):聚集写入,把缓冲区position到limit之间的数据依次的写入到管道中。
这样,一个大文件就可以分割成许多小的文件进行传输。
其示意图如下:
Java NIO的Scatter与Gather_第1张图片

Java NIO的Scatter与Gather_第2张图片

代码实现如下:

public class Demo06_ScotterAndGather {
      public static void main(String[] args) throws IOException {
        RandomAccessFile raf1=new RandomAccessFile("hello2.txt", "rw");
        //获取通道
        FileChannel channel1 = raf1.getChannel();
        //设置缓冲区
        ByteBuffer buf1=ByteBuffer.allocate(50);
        ByteBuffer buf2=ByteBuffer.allocate(1024);
        //分散读取的时候缓存区应该事有序的,所以把几个缓冲区加入数组中
        ByteBuffer[] bufs={buf1,buf2};
        //通道进行传输
        channel1.read(bufs);

        //查看缓冲区中的内容
        for (int i = 0; i < bufs.length; i++) {
            //切换为读模式
            bufs[i].flip();
        }

        System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
        System.out.println();
        System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));

        //聚集写入
        RandomAccessFile  raf2=new RandomAccessFile("ScoAndGat.txt", "rw");
        FileChannel channel2 = raf2.getChannel();
        //只能通过通道来进行写入
        channel2.write(bufs);
      }
}

你可能感兴趣的:(JAVA那些事,JAVA,NIO)