JAVA高階基礎(49)---分散讀取和聚集寫入
阿新 • • 發佈:2018-12-15
分散讀取和聚集寫入
- read(ByteBuffer[] bufs); //分散讀取
- write(ByteBuffer[] bufs); //聚集寫入
分散讀取(Scattering Reads)是指從Channle中讀取的資料“分散”到多個Buffer中
注意:按照緩衝區的順序,從Channle中讀取的資料依次將Buffer填滿
聚集寫入(Gathering Writes)是指將多個Buffer中的資料“聚集”到Channle
注意:按照緩衝區的順序,寫入 position 和 limit 之間的資料到 Channle
package org.lanqiao.channel.demo; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /* * 分散讀取和聚集寫入 */ public class ChannelDemo { public static void main(String[] args) throws IOException { //開闢通道: RandomAccessFile raf = new RandomAccessFile("Notes.txt","rw"); RandomAccessFile rafOut = new RandomAccessFile("copy.txt", "rw"); FileChannel inChannel = raf.getChannel(); FileChannel outChannel = rafOut.getChannel(); //分配緩衝區: ByteBuffer buf1 = ByteBuffer.allocate(100); ByteBuffer buf2 = ByteBuffer.allocate(1024); ByteBuffer buf3 = ByteBuffer.allocate(100); ByteBuffer[] bufs = {buf1 , buf2,buf3}; while((inChannel.read(bufs)) != -1) { for(ByteBuffer bb :bufs) { bb.flip(); System.out.println(new String(bb.array(),0,bb.limit())); bb.clear(); System.out.println("-------------------------------------"); } System.out.println("++++++++++++++++++++++++++"); } /*//進行讀操作 while((inChannel.read(bufs)) != -1) { for(ByteBuffer bb :bufs) { bb.flip(); outChannel.write(bb); bb.clear(); } }*/ inChannel.close(); outChannel.close(); } }