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中执行数据收集

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

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

技术教程推荐

机器学习40讲 -〔王天一〕

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

许式伟的架构课 -〔许式伟〕

分布式数据库30讲 -〔王磊〕

Linux内核技术实战课 -〔邵亚方〕

WebAssembly入门课 -〔于航〕

分布式金融架构课 -〔任杰〕

流程型组织15讲 -〔蒋伟良〕

Midjourney入门实践课 -〔Jovi〕

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