分散读取(Scattering Reads)是指从 Channel 中读取的数据“分散”到多个 Buffer 中。
数据从通道写入到各个缓冲区中,依次填满0->1->2缓冲区,下面我们通过程序来实现这一操作:
RandomAccessFile raf1=new RandomAccessFile("F:\\NIO\\nio\\a.txt","rw"); FileChannel channel1=raf1.getChannel(); //获取通道 ByteBuffer buf1=ByteBuffer.allocate(512); ByteBuffer buf2=ByteBuffer.allocate(1024); //分散读取 ByteBuffer[] bufs={buf1,buf2}; try { channel1.read(bufs); } catch (IOException e) { e.printStackTrace(); } for (ByteBuffer byteBuffer:bufs){ byteBuffer.flip(); } System.out.println(new String(bufs[0].array(),0,bufs[0].limit())); System.out.println("-------------------------"); System.out.println(new String(bufs[1].array(),0,bufs[1].limit())); 打印输出结果:
聚集写入:
所谓聚集写入(Gathering Writes)是指将多个 Buffer 中的数据“聚集”到 Channel。
实现代码:
RandomAccessFile randomAccessFile=new RandomAccessFile("F:\\NIO\\nio\\b.txt","rw"); FileChannel channal2=randomAccessFile.getChannel(); try { channal2.write(bufs); } catch (IOException e) { e.printStackTrace(); }