zoukankan      html  css  js  c++  java
  • 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();
            }
        }

     

  • 相关阅读:
    内容生成器.计数器及多列
    STT-MTJ(自旋转移矩磁隧道结)模型的Verilog-A语言描述(仅参考)
    将进酒-唐·李白
    三十六计、孙子兵法
    Keil新建工程步骤
    No.6 Verilog 其他论题
    2-4 Numpy+Matplotlib可视化(二)
    2-3 Numpy+Matplotlib可视化(一)
    0-0 列表,元组,字典,集合
    2-2 Numpy-矩阵
  • 原文地址:https://www.cnblogs.com/shamo89/p/9612875.html
Copyright © 2011-2022 走看看