Monday 10 June 2019

Nio: Get the remaining element in the buffer


Buffer class provides 'remaining' method, it returns the number of elements between the current position and the limit.

Find the below working application.

Test.java
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

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

  /* Add elements to the buffer */
  byteBuffer.put((byte) 'H');
  byteBuffer.put((byte) 'E');
  byteBuffer.put((byte) 'L');
  byteBuffer.put((byte) 'L');
  byteBuffer.put((byte) 'O');

  int remainingEle = byteBuffer.remaining();
  System.out.println("position : " + byteBuffer.position() + ", limit : " + byteBuffer.limit());
  System.out.println("Remaining Elements : " + remainingEle);

  System.out.println("\nSetting the position to 0");
  byteBuffer.position(0);
  remainingEle = byteBuffer.remaining();
  System.out.println("position : " + byteBuffer.position() + ", limit : " + byteBuffer.limit());
  System.out.println("Remaining Elements : " + remainingEle);

  System.out.println("\nSetting the limit to 3");
  byteBuffer.limit(3);
  remainingEle = byteBuffer.remaining();
  System.out.println("position : " + byteBuffer.position() + ", limit : " + byteBuffer.limit());
  System.out.println("Remaining Elements : " + remainingEle);

 }
}

Output
position : 5, limit : 5
Remaining Elements : 0

Setting the position to 0
position : 0, limit : 5
Remaining Elements : 5

Setting the limit to 3
position : 0, limit : 3
Remaining Elements : 3


Previous                                                 Next                                                 Home

No comments:

Post a Comment