zoukankan      html  css  js  c++  java
  • 6、NIO--分散读取与聚集写入

    分散读取

    分散读取(Scattering Reads)是指从 Channel 中读取的数据“分
    散”到多个 Buffer 中。

     注意:按照缓冲区的顺序,从 Channel 中读取的数据依次将 Buffer 填满。

    聚集写入

    聚集写入(Gathering Writes)是指将多个 Buffer 中的数据“聚集”
    到 Channel

    注意:按照缓冲区的顺序,写入 position 和 limit 之间的数据到 Channel 。

    测试小实例:

    //分散读取和聚集写入
        @Test
        public void test7() throws IOException {
            
            RandomAccessFile raf = new RandomAccessFile("d:\a.txt","rw");
            
            //1、获取通道
            FileChannel fileChannel = raf.getChannel();
            
            //2、分配指定大小的缓冲区
            ByteBuffer buf1= ByteBuffer.allocate(20);
            ByteBuffer buf2 = ByteBuffer.allocate(200);
            
            //3、分散读取
            ByteBuffer [] bufs = {buf1,buf2};
            //read(ByteBuffer[] dsts) 
            fileChannel.read(bufs);
            
            for(ByteBuffer b : bufs){
                b.flip();
            }
            
            System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
            System.out.println(new String(bufs[1].array(),0,bufs[1].limit()));
            
            //聚集写入
            RandomAccessFile raf2 = new RandomAccessFile("d:\aa.txt", "rw");
            FileChannel fileChannel2 = raf2.getChannel();
            //write(ByteBuffer[] srcs)
            fileChannel2.write(bufs);
            
        }

     控制台的打印:

    文件的写入:

     

  • 相关阅读:
    C#的list和arry相互转化
    c++11の的左值、右值以及move,foward
    c++11の异步方法 及线程间通信
    C#的static
    HDU4027 Can you answer these queries?
    POJ3264 Balances Lineup
    ZOJ1610 Count the Colors
    ZOJ4110 Strings in the Pocket(2019浙江省赛)
    HDU1698 Just a Hook
    POJ3468 A Simple Problem with Integers
  • 原文地址:https://www.cnblogs.com/Mrchengs/p/10825048.html
Copyright © 2011-2022 走看看