Java NIO分散读 聚集写

#Java NIO分散读 聚集写


Java NIO 开始支持scatter/gather(分散读/聚集写),scatter/gather用于描述从channel中读取或者写入到channel的操作。

1. 概念

分散(scatter)从channel中读取是指在读操作的时候将读取的数据写入到多个buffer中,因此,channel将读取到的数据分散到多个buffer中。当一个buffer被写满之后,才会进行下一个buffer的写入。

图片描述

聚集(scatter)是指将多个 Buffer 中的数据“聚集”到 Channel。一个buffer读完之后,才会进行下一个buffer的读入

图片描述

2. 代码

public class ScatterReadAndGatheringWrite {
    public static void main(String[] args) {
        String src1 = "src/file.txt";
        String src2 = "src/file.copy.txt";
        ByteBuffer byteBuffer1 = ByteBuffer.allocate(1);
        ByteBuffer byteBuffer2 = ByteBuffer.allocate(100);
        byteBuffer1.clear();
        byteBuffer2.clear();
        ByteBuffer[] bufs={byteBuffer1, byteBuffer2};

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(src1);
            FileChannel inChannel = fileInputStream.getChannel();

            fileOutputStream = new FileOutputStream(src2);
            FileChannel outChannel = fileOutputStream.getChannel();

            while (true) {

                //开始写数据到buffer中
                long r = inChannel.read(bufs);
                System.out.println(r);
                if (r == 0) {
                    break;
                }

                //切换到读模式
                for (ByteBuffer buffer : bufs) {
                    buffer.flip();
                }

                //System.out.println("buffer.position=" + byteBuffer1.position());
                //System.out.println("buffer.capacity=" + byteBuffer1.capacity());
                //System.out.println("buffer.limit=" + byteBuffer1.limit());
                outChannel.write(bufs);

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

3. 参考文章

https://blog.csdn.net/qq_33804730/article/details/79171188
https://blog.csdn.net/jkxqj/article/details/77480006

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值