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

    image.png

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


    image.png

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