分散读取与聚集写入

分散读取与聚集写入

分散读取(scattering Reads):将通道中的数据分散到多个缓冲区中

聚集写入(gathering Writes):将多个缓冲区的数据聚集到通道中

package com.toov5.Nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class BufferTest03 {
   public static void main(String[] args) throws IOException {
       //随机访问
     RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
     //拿到通道
      FileChannel channel = raf.getChannel();
      //分配制定大小缓冲区
      ByteBuffer buffer1 = ByteBuffer.allocate(100);
      ByteBuffer buffer2 = ByteBuffer.allocate(1024);
      //分散读取
      ByteBuffer[] buffers = {buffer1,buffer2}; 
      //通道里面进行读取
       channel.read(buffers);
       //写入完毕之后 for 循环
       for(ByteBuffer byteBuffer : buffers) {
          //切换成读的模式
           byteBuffer.flip();
            
       }
       System.out.println(new String(buffers[0].array(),0,buffers[0].limit()));
       System.out.println("*****************************************");
       System.out.println(new String(buffers[1].array(),1,buffers[1].limit()));
       System.out.println(".....聚集读取.........");
       RandomAccessFile randomAccessFile = new RandomAccessFile("test2.txt", "rw");
       //获取通道
       FileChannel channel2 = randomAccessFile.getChannel();
       channel2.write(buffers);
       randomAccessFile.close();
       raf.close();
}
}

 

 分散读取 聚集写入

 

posted @ 2018-11-08 23:37  toov5  阅读(568)  评论(0编辑  收藏  举报