Thursday, 13 June 2019

Nio: Buffer slicing

You can create a sub buffer from existing buffer using slice() method. Sliced buffer and original buffer shares same data. That is Modifications to the sliced buffer will cause the original buffer to be modified and vice versa. 

ByteBuffer byteBuffer = ByteBuffer.allocate(10);

byteBuffer.put((byte) 2);
byteBuffer.put((byte) 3);
byteBuffer.put((byte) 5);
byteBuffer.put((byte) 7);

ByteBuffer slicedBuffer = byteBuffer.slice();

Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;

public class Test {

 private static void printMetaInfo(String message, ByteBuffer byteBuffer) {
  System.out.println(message);
  System.out.printf("Limit : %d\n", byteBuffer.limit());
  System.out.printf("Capacity : %d\n", byteBuffer.capacity());
  System.out.printf("Position : %d\n", byteBuffer.position());
 }

 private static void printBuffer(String message, ByteBuffer byteBuffer) {
  System.out.println(message);
  for (int i = 0; i < byteBuffer.capacity(); i++) {
   System.out.print(byteBuffer.get(i) + " ");
  }
  System.out.println();
 }

 public static void main(String... args) throws IOException {
  ByteBuffer byteBuffer = ByteBuffer.allocate(10);

  byteBuffer.put((byte) 2);
  byteBuffer.put((byte) 3);
  byteBuffer.put((byte) 5);
  byteBuffer.put((byte) 7);

  ByteBuffer slicedBuffer = byteBuffer.slice();

  String msg = "Meta information of the buffer";
  printMetaInfo(msg, byteBuffer);

  msg = "Content of the buffer";
  printBuffer(msg, byteBuffer);

  msg = "\nMeta information of the sliced buffer";
  printMetaInfo(msg, slicedBuffer);

  msg = "Content of the sliced buffer";
  printBuffer(msg, slicedBuffer);
  
  byteBuffer.put((byte)11);
  byteBuffer.put((byte)13);
  
  System.out.println("\nAdded 2 more elements into the buffer");
  
  msg = "\nMeta information of the buffer";
  printMetaInfo(msg, byteBuffer);

  msg = "Content of the buffer";
  printBuffer(msg, byteBuffer);

  msg = "\nMeta information of the sliced buffer";
  printMetaInfo(msg, slicedBuffer);

  msg = "Content of the sliced buffer";
  printBuffer(msg, slicedBuffer);
 }
}


Output

Meta information of the buffer
Limit : 10
Capacity : 10
Position : 4
Content of the buffer
2 3 5 7 0 0 0 0 0 0

Meta information of the sliced buffer
Limit : 6
Capacity : 6
Position : 0
Content of the sliced buffer
0 0 0 0 0 0

Added 2 more elements into the buffer

Meta information of the buffer
Limit : 10
Capacity : 10
Position : 6
Content of the buffer
2 3 5 7 11 13 0 0 0 0

Meta information of the sliced buffer
Limit : 6
Capacity : 6
Position : 0
Content of the sliced buffer
11 13 0 0 0 0



Previous                                                 Next                                                 Home

No comments:

Post a Comment