NIO之Channel聚集(gather)写入与分散(scatter)读取

Channel聚集(gather)写入

聚集写入( Gathering Writes)是指将多个 Buffer 中的数据“聚集”到 Channel。 特别注意:按照缓冲区的顺序,写入 position 和 limit 之间的数据到 Channel 。 

Channel分散(scatter)读取

分散读取( Scattering Reads)是指从 Channel 中读取的数据“分散” 到多个 Buffer 中。 特别注意:按照缓冲区的顺序,从 Channel 中读取的数据依次将 Buffer 填满。


 

聚集写入( Gathering Writes和分散读取( Scattering Reads)代码示例

// 分散读取聚集写入实现文件复制
    public static void main(String[] args){
        RandomAccessFile randomAccessFile = null;
        RandomAccessFile randomAccessFile1 = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            randomAccessFile = new RandomAccessFile(new File("d:\\old.txt"), "rw");
            randomAccessFile1 = new RandomAccessFile(new File("d:\\new.txt"), "rw");
            inChannel = randomAccessFile.getChannel();
            outChannel = randomAccessFile1.getChannel();
            // 分散为三个bytebuffer读取,capcity要设置的足够大,不然如果文件太大,会导致复制的内容不完整
            ByteBuffer byteBuffer1 = ByteBuffer.allocate(1024);
            ByteBuffer byteBuffer2 = ByteBuffer.allocate(1024);
            ByteBuffer byteBuffer3 = ByteBuffer.allocate(10240);
            ByteBuffer[] bbs = new ByteBuffer[]{byteBuffer1,byteBuffer2,byteBuffer3};
            
            inChannel.read(bbs);// 分散读取
            
            // 切换为写入模式
            for (int i = 0; i < bbs.length; i++) {
                bbs[i].flip();
            }
            
            outChannel.write(bbs);
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

 

 

转载于:https://www.cnblogs.com/shamo89/p/9612875.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值