NIO——第三弹

Java NIO Scatter / /分散聚拢Gather//集合在一起
作用主要是在从channel里面读取数据,和将数据写入channel

basic exmaple  for Scattering Reads
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body   = ByteBuffer.allocate(1024);

ByteBuffer[] bufferArray = { header, body };

channel.read(buffers);
//说明读取到第一个之后,将会继续读到下一个,如果你的第一个buffer大小固定,那么第二个buffer散射的就会更好

basic exmple for Gathering Writes
ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body   = ByteBuffer.allocate(1024);

//将数据写入channel中,假如buffer中的数据只有58,而容量有126,则就会把58的数据写入buffer中
NIO——第三弹_第1张图片ByteBuffer[] bufferArray = { header, body };

channel.write(buffers);
NIO——第三弹_第2张图片Java NIO Channel to Channel Transfers//直接利用通道之间相互传递数据

basic //transferFrom()目标在前,源在后
RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel      toChannel = toFile.getChannel();

long position = 0;
long count    = fromChannel.size();

toChannel.transferFrom(fromChannel, position, count);//此外对于socketChannel类型的数据,其内部有固定的缓冲区,不会将所有的数据全部传输到fileChannel中


The transferTo()//方法的例子

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel      toChannel = toFile.getChannel();

long position = 0;
long count    = fromChannel.size();

fromChannel.transferTo(position, count, toChannel);

你可能感兴趣的:(NIO——第三弹)