Saturday 8 June 2019

Nio: Buffer: flip(): Flip the stream


When you call the flip() method on a buffer, below things will be taken place.
         a. Set the limit to current position.
         b. Set the current position to zero.
         c. mark will be set to undefined state (mark = -1).

Find the below working application.

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.flip();

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

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

  byteBuffer.flip();

  System.out.println("After calling flip() api again 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 flip() api on the buffer
position : 0, limit : 26


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


After calling flip() api again on the buffer
position : 0, limit : 0





Previous                                                 Next                                                 Home

No comments:

Post a Comment