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——第三弹ByteBuffer[] bufferArray = { header, body };

channel.write(buffers);
NIO——第三弹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);

转载于:https://my.oschina.net/u/876290/blog/367999

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-05
  • 2021-09-20
  • 2022-02-14
  • 2021-10-13
  • 2021-05-04
猜你喜欢
  • 2021-06-23
  • 2022-03-06
  • 2022-12-23
  • 2022-12-23
  • 2021-06-04
  • 2021-06-26
  • 2021-12-28
相关资源
相似解决方案