package com.sico.pck01_nio;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.junit.Test;
/**
-
@author Administrator
-
分散读取(Scatter):将通道中的数据分散到各个缓冲区中去(按照顺序填充);聚集写入(Gather):将各个缓冲区中的数据聚集到通道中
*/
public class Nio03 {@Test
public void fun01() throws IOException{//1、分散讀取 RandomAccessFile raf01 = new RandomAccessFile("./file/1.txt", "rw"); FileChannel channel1 = raf01.getChannel(); ByteBuffer buf1 = ByteBuffer.allocate(100); ByteBuffer buf2 = ByteBuffer.allocate(1024); ByteBuffer[] bufArr={buf1,buf2}; channel1.read(bufArr); for(ByteBuffer ele:bufArr){ ele.flip();//切換模式 } System.out.println(new String(bufArr[0].array(),0,bufArr[0].limit())); System.out.println(); System.out.println(new String(bufArr[1].array(),0,bufArr[1].limit())); System.out.println("***********************************************"); //2、聚集寫入 RandomAccessFile raf2=new RandomAccessFile("./file/2.txt", "rw"); FileChannel channel2 = raf2.getChannel(); channel2.write(bufArr); if(raf01!=null){ raf01.close(); } if(channel1!=null){ channel1.close(); }
}
}