package com.xbb.demo;
import org.junit.Test;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* 五 : 分散(Scatter) 与聚集 (Gather)
* 分散读取(Scattering Reads) : 将通道中的数据分散到多个缓冲区中
* 聚集写入(Gathering Writes) : 将多个缓冲区中的数据聚集到通道中
*
* 注意 : 按照缓冲区的顺序,从Channel中读取的数据今次将Buffer填满
*/
public class ScatterAndGatherDemo {
/**
* 分散读取
*/
@Test
public void scatterTest(){
try(
RandomAccessFile raf = new RandomAccessFile("/Users/riverjin/java_pro/nio/src/main/java/com/xbb/demo/ChannelDemo.java","rw");
FileChannel rafChannel = raf.getChannel();
){
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(10240);
ByteBuffer[] bufs = {buf1,buf2};
rafChannel.read(bufs);
for (ByteBuffer buf: bufs) {
buf.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()));
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 聚集写入
*/
@Test
public void gatherTest(){
try(
RandomAccessFile rafR = new RandomAccessFile("/Users/riverjin/java_pro/nio/src/main/java/com/xbb/demo/ChannelDemo.java","rw");
RandomAccessFile rafW = new RandomAccessFile("/Users/riverjin/java_pro/nio/src/main/java/com/xbb/demo/ChannelDemo2.java","rw");
FileChannel rChannel = rafR.getChannel();
FileChannel wChannel = rafW.getChannel();
){
ByteBuffer buf1 = ByteBuffer.allocate(500);
ByteBuffer buf2 = ByteBuffer.allocate(10240);
ByteBuffer[] bufs = {buf1,buf2};
rChannel.read(bufs);
for (ByteBuffer buf : bufs) {
buf.flip();
}
wChannel.write(bufs);
}catch (Exception e){
e.printStackTrace();
}
}
}
NIO(四) - 分散(Scatter) 与聚集 (Gather)
最新推荐文章于 2024-07-06 09:46:05 发布