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

时间:2022-12-31 08:21:27
  • 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测试:
 1 @Test
 2     public void testGatherScatter() throws IOException {
 3         RandomAccessFile randomAccessFile = new RandomAccessFile("d:\\ce.txt", "rw");
 4         // 获取通道
 5         FileChannel channel = randomAccessFile.getChannel();
 6 
 7         // 申请缓存空间
 8         ByteBuffer byteBuffer00 = ByteBuffer.allocate(128);
 9         ByteBuffer byteBuffer01 = ByteBuffer.allocate(1024);
10 
11         // 通过channel.read(ByteBuffer[] byteBuffers),将数据分散读取到byteBuffer00,byteBuffer01
13         ByteBuffer[] byteBuffers = { byteBuffer00, byteBuffer01 };
14         channel.read(byteBuffers);
15 
16         for (ByteBuffer byteBuffer : byteBuffers) {
17             byteBuffer.flip();
18         }
19 
20         System.out.println(new String(byteBuffers[0].array(), 0, byteBuffers[0].limit()));
21         System.out.println("-----------------------------------------------------------");
22         System.out.println(new String(byteBuffers[1].array(), 0, byteBuffers[1].limit()));
23 
24         // 聚集写入
25         RandomAccessFile randomAccessFile2 = new RandomAccessFile("d:\\ce_copy.txt", "wr");
26         // 1、获取管道
27         FileChannel channel2 = randomAccessFile2.getChannel();
28 
29         // 2、通过管道将数据写入
30         channel2.write(byteBuffers);
31 
32         channel2.close();
33         channel.close();
34     }