Thursday, 13 June 2019

NIO: Get the buffer contents as an array

Buffer class provides 'array' method, by using this you can get an array that backs this buffer.

When you modify the returned array content, you can see the changes in the buffer.

When you modify the buffer content, then the changes will be reflected in the returned array.

Find the below working application.

Test.java
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

 private static void printBufferContents(ByteBuffer byteBuffer) {

  byteBuffer.clear();

  System.out.print("Buffer Content : ");
  while (byteBuffer.hasRemaining()) {
   byte b = byteBuffer.get();
   System.out.print((char) b + "");
  }

  System.out.println();
 }

 private static void printArrayContents(byte[] arr) {
  System.out.print("Array Elments : ");
  for (byte b : arr) {
   System.out.print((char) b + "");
  }
  System.out.println();
 }

 public static void main(String args[]) throws Exception {
  ByteBuffer byteBuffer = ByteBuffer.allocate(5);

  byteBuffer.put((byte) 'H');
  byteBuffer.put((byte) 'E');
  byteBuffer.put((byte) 'L');
  byteBuffer.put((byte) 'L');
  byteBuffer.put((byte) 'O');

  printBufferContents(byteBuffer);

  byte[] backedArray = byteBuffer.array();
  printArrayContents(backedArray);

  System.out.println("\nAfter Modifying\n");

  backedArray[0] = (byte) 'I';
  backedArray[1] = (byte) 'N';

  byteBuffer.put(2, (byte) 'B');
  byteBuffer.put(3, (byte) 'O');
  byteBuffer.put(4, (byte) 'X');

  printBufferContents(byteBuffer);
  printArrayContents(backedArray);
 }
}


Output
Buffer Content : HELLO
Array Elments : HELLO

After Modifying

Buffer Content : INBOX
Array Elments : INBOX



Previous                                                 Next                                                 Home

No comments:

Post a Comment