Java NIO - Gather(聚集)

Java NIO - Gather(聚集) 首页 / Nio入门教程 / Java NIO - Gather(聚集)

Java NIO是一种针对数据IO操作进行了更优化处理的API,Java NIO支持是从多个缓冲区读取数据或向多个缓冲区写入数据或将数据写入通道。写入支持称为"分散和聚集",其中在读取数据的情况下,数据从单个通道分散到多个缓冲区,在写入数据的情况下,数据从多个缓冲区收集到单个通道。

为了实现从通道的多次读写,Java NIO提供了ScatteringByteChannelGatheringByteChannel API,NIO提供了该API来读写数据,如以下示例所示。

GatheringByteChannel

无涯教程将数据从多个缓冲区写入单个通道,为此,再次分配了多个缓冲区并将其添加到缓冲数组中,然后将该数组作为参数传递到GatheringByteChannel write()方法,该方法按照缓冲区在数组中出现的顺序从多个缓冲区写入数据。这里要记住的一点是,仅写入缓冲区的位置和限制之间的数据。

以下示例显示了如何在Java NIO中执行数据收集

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/java-nio/java-nio-gather.html

来源:LearnFk无涯教程网

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;

public class GatherExample {
   private static String FILENAME = "C:/Test/temp.txt";
   public static void main(String[] args) {
      String stream1 = "Gather data stream first";
      String stream2 = "Gather data stream second";
      ByteBuffer bLen1 = ByteBuffer.allocate(1024);
      ByteBuffer bLen2 = ByteBuffer.allocate(1024);
      // 接下来的两个缓冲区保存无涯教程要写入的数据
      ByteBuffer bstream1 = ByteBuffer.wrap(stream1.getBytes());
      ByteBuffer bstream2 = ByteBuffer.wrap(stream2.getBytes());
      int len1 = stream1.length();
      int len2 = stream2.length();
      // 将长度(数据)写入缓冲区
      bLen1.asIntBuffer().put(len1);
      bLen2.asIntBuffer().put(len2);
      System.out.println("Gathering : Len1 = " + len1);
      System.out.println("Gathering : Len2 = " + len2);
      // 将数据写入文件
      try { 
         FileOutputStream out = new FileOutputStream(FILENAME);
         GatheringByteChannel gather = out.getChannel();            
         gather.write(new ByteBuffer[] {bLen1, bLen2, bstream1, bstream2});
         out.close();
         gather.close();
      }
      catch (FileNotFoundException exObj) {
         exObj.printStackTrace();
      }
      catch(IOException ioObj) {
         ioObj.printStackTrace();
      }
   }
}

运行上面代码输出

Gathering : Len1=24
Gathering : Len2=25

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

趣谈网络协议 -〔刘超〕

Go语言从入门到实战 -〔蔡超〕

Swift核心技术与实战 -〔张杰〕

Node.js开发实战 -〔杨浩〕

后端存储实战课 -〔李玥〕

编译原理实战课 -〔宫文学〕

深度学习推荐系统实战 -〔王喆〕

说透数字化转型 -〔付晓岩〕

现代React Web开发实战 -〔宋一玮〕

好记忆不如烂笔头。留下您的足迹吧 :)