Java-NIO(六):Channel聚集(gather)写入与分散(scatter)读取

时间:2024-10-05 23:04:08
  • Channel聚集(gather)写入:

聚集写入( Gathering Writes)是指将多个 Buffer 中的数据“聚集”到 Channel。 特别注意:按照缓冲区的顺序,写入 position 和 limit 之间的数据到 Channel 。

Java-NIO(六):Channel聚集(gather)写入与分散(scatter)读取

  • Channel分散(scatter)读取:

分散读取( Scattering Reads)是指从 Channel 中读取的数据“分散” 到多个 Buffer 中。 特别注意:按照缓冲区的顺序,从 Channel 中读取的数据依次将 Buffer 填满。

Java-NIO(六):Channel聚集(gather)写入与分散(scatter)读取

  • 聚集写入( Gathering Writes)和分散读取( Scattering Reads)测试:
 @Test
public void testGatherScatter() throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile("d:\\ce.txt", "rw");
// 获取通道
FileChannel channel = randomAccessFile.getChannel(); // 申请缓存空间
ByteBuffer byteBuffer00 = ByteBuffer.allocate(128);
ByteBuffer byteBuffer01 = ByteBuffer.allocate(1024); // 通过channel.read(ByteBuffer[] byteBuffers),将数据分散读取到byteBuffer00,byteBuffer01
ByteBuffer[] byteBuffers = { byteBuffer00, byteBuffer01 };
channel.read(byteBuffers); for (ByteBuffer byteBuffer : byteBuffers) {
byteBuffer.flip();
} System.out.println(new String(byteBuffers[0].array(), 0, byteBuffers[0].limit()));
System.out.println("-----------------------------------------------------------");
System.out.println(new String(byteBuffers[1].array(), 0, byteBuffers[1].limit())); // 聚集写入
RandomAccessFile randomAccessFile2 = new RandomAccessFile("d:\\ce_copy.txt", "wr");
// 1、获取管道
FileChannel channel2 = randomAccessFile2.getChannel(); // 2、通过管道将数据写入
channel2.write(byteBuffers); channel2.close();
channel.close();
}