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