版权声明:如需转载请标明出处 https://blog.csdn.net/yj201711/article/details/84955838
分散读取和聚集写入
- 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();
}
}