Monday 10 June 2019

Nio: Set the current position of the buffer

By using 'position' method, you can set the current position of the buffer. Element are added from the current position of the buffer.

Find the below working application.

Test.java
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

 private static void printBuffer(ByteBuffer byteBuffer) {
  byte[] arr = byteBuffer.array();

  for (byte b : arr) {
   System.out.println(b);
  }
 }

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

  System.out.println("Current position of the buffer " + byteBuffer.position());

  printBuffer(byteBuffer);

  System.out.println("Setting the current position to 5");
  byteBuffer.position(5);
  System.out.println("Current position of the buffer " + byteBuffer.position());
  
  System.out.println("Adding two elements to the buffer");
  byteBuffer.put((byte) 72);
  byteBuffer.put((byte) 73);

  printBuffer(byteBuffer);
  System.out.println("Current position of the buffer " + byteBuffer.position());

 }
}


Output

Current position of the buffer 0
0
0
0
0
0
0
0
0
0
0
Setting the current position to 5
Current position of the buffer 5
Adding two elements to the buffer
0
0
0
0
0
72
73
0
0
0
Current position of the buffer 7


Previous                                                 Next                                                 Home

No comments:

Post a Comment