1. 程式人生 > >Java-NIO(六):Channel聚集(gather)寫入與分散(scatter)讀取

Java-NIO(六):Channel聚集(gather)寫入與分散(scatter)讀取

 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 }