首页 > 代码库 > JAVA NIO Scatter/Gather(矢量IO)

JAVA NIO Scatter/Gather(矢量IO)

矢量IO=Scatter/Gather:
 
在多个缓冲区上实现一个简单的IO操作。减少或避免了缓冲区拷贝和系统调用(IO)
 
write:Gather
数据从几个缓冲区顺序抽取并沿着通道发送,就好比全部缓冲区全部连接起来放入一个大的缓冲区进行发送,缓冲区本身不具备gather能力。
read:Scatter
从通道读取的数据会按顺序散布到多个缓冲区,直到缓冲区被填满或者通道数据读完。
 技术分享

 

技术分享
Gather:
技术分享
技术分享
Scatter:
技术分享
技术分享
示例代码:
 
 1 /**
 2      * channel Gather/Scatter
 3      */
 4     public static void channelGatherScatter(){
 5         ByteBuffer head = ByteBuffer.allocate(4);
 6         ByteBuffer body = ByteBuffer.allocate(100);
 7         RandomAccessFile afile = null;
 8         RandomAccessFile bfile = null;
 9         ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
10         try {
11             afile = new RandomAccessFile("hello.txt", "r");
12             bfile = new RandomAccessFile("hehe.txt", "rw");
13             readWriteLock.readLock().lock();
14             FileChannel fileChannel = afile.getChannel();
15             ByteBuffer[] buffers = {head, body};
16             while (fileChannel.read(buffers) != -1){
17             }
18             head.flip();
19             body.flip();
20             System.out.println(new String(head.array()));
21             System.out.println(new String(body.array()));
22             readWriteLock.readLock().unlock();
23             fileChannel.close();
24             afile.close();
25 
26             readWriteLock.writeLock().lock();
27             FileChannel bfileChannel = bfile.getChannel();
28 
29             while (bfileChannel.write(buffers) > 0){
30             }
31 
32             readWriteLock.writeLock().unlock();
33             bfileChannel.close();
34             bfile.close();
35         }catch (Exception e){
36             e.printStackTrace();
37         }
38     }
 
带offset、length参数重载read write方法,指明从那个buffer开始,共使用多少个buffer。
 
 

JAVA NIO Scatter/Gather(矢量IO)