Java NIO - Recopilar

Como sabemos, Java NIO es una API más optimizada para operaciones de E / S de datos en comparación con la API de E / S convencional de Java. Un soporte adicional más que proporciona Java NIO es leer / escribir datos desde / hacia múltiples búferes al canal. y el soporte de escritura se denomina Scatter and Gather, en el que los datos se dispersan en múltiples búferes de un solo canal en caso de leer datos, mientras que los datos se recopilan de múltiples búferes a un solo canal en caso de escribir datos.

Para lograr esta lectura y escritura múltiples desde el canal, existe la API ScatteringByteChannel y GatheringByteChannel que Java NIO proporciona para leer y escribir los datos como se ilustra en el siguiente ejemplo.

GatheringByteChannel

write to multiple channels - En esto hicimos escribir datos de múltiples búferes en un solo canal. Para esto nuevamente se asignan múltiples búferes y se agregan a una matriz de tipo de búfer. Luego esta matriz se pasa como parámetro al método GatheringByteChannel write () que luego escribe datos de los múltiples búferes en la secuencia, los búferes ocurren en la matriz. Un punto a recordar aquí es que solo se escriben los datos entre la posición y el límite de los búferes.

El siguiente ejemplo muestra cómo se realiza la recopilación de datos en 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);
      // Next two buffer hold the data we want to write
      ByteBuffer bstream1 = ByteBuffer.wrap(stream1.getBytes());
      ByteBuffer bstream2 = ByteBuffer.wrap(stream2.getBytes());
      int len1 = stream1.length();
      int len2 = stream2.length();
      // Writing length(data) to the Buffer
      bLen1.asIntBuffer().put(len1);
      bLen2.asIntBuffer().put(len2);
      System.out.println("Gathering : Len1 = " + len1);
      System.out.println("Gathering : Len2 = " + len2);
      // Write data to the file
      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();
      }
   }
}

Salida

Gathering : Len1 = 24
Gathering : Len2 = 25

Por último, se puede concluir que el enfoque de dispersión / recopilación en Java NIO se presenta como un método optimizado y multitarea cuando se usa correctamente. Le permite delegar en el sistema operativo el trabajo duro de separar los datos que lee en múltiples cubos o ensamblar fragmentos dispares de datos en un todo. Sin duda, esto ahorra tiempo y usa el sistema operativo de manera más eficiente al evitar copias en búfer y reduce la cantidad de código necesario para escribir y depurar.