Friday, 7 June 2019

Nio: Buffer: clear() : set the current position back to 0


By calling the clear() method on buffer object, you can perform below things in one shot.
a.   Set the current position back to 0.
b.   Set the limit of the buffer to capacity (Capacity of the buffer is set at the time of creation)
c.    Set the mark value to -1 (mark will be undefined state).

Test.java
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

 private static final String ALPHABETS = "abcdefghijklmnopqrstuvwxyz";

 private static void printStats(ByteBuffer byteBuffer) {
  int currentPosition = byteBuffer.position();
  int activeElePosition = byteBuffer.limit();
  System.out.println("position : " + currentPosition + ", limit : " + activeElePosition);
  System.out.println("\n");
 }

 public static void main(String args[]) throws Exception {
  /* Define new byte buffer of capacity 11 */
  ByteBuffer byteBuffer = ByteBuffer.allocate(26);
  System.out.println("Before inserting the data into buffer");
  printStats(byteBuffer);

  for (int i = 0; i < ALPHABETS.length(); i++) {
   byteBuffer.put((byte) ALPHABETS.charAt(i));
  }
  System.out.println("After inserting 26 characters into the buffer");
  printStats(byteBuffer);

  byteBuffer.clear();

  System.out.println("After calling clear() api on the buffer");
  printStats(byteBuffer);

  System.out.println("Setting the limit to 10");
  byteBuffer.limit(10);
  printStats(byteBuffer);

  byteBuffer.clear();

  System.out.println("After calling clear() api on the buffer");
  printStats(byteBuffer);

 }
}


Output

Before inserting the data into buffer
position : 0, limit : 26


After inserting 26 characters into the buffer
position : 26, limit : 26


After calling clear() api on the buffer
position : 0, limit : 26


Setting the limit to 10
position : 0, limit : 10


After calling clear() api on the buffer
position : 0, limit : 26




Previous                                                 Next                                                 Home

No comments:

Post a Comment