Friday 7 June 2019

Buffer: Marking and resetting


We can mark the buffer current position using mark() method. At any point of time, you can change the current position to the marked point by calling the reset method.

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("Reading first five characters from buffer");
  /* Read first five characters from buffer */
  for (int i = 0; i < 5; i++) {
   System.out.println((char) byteBuffer.get());
  }

  printStats(byteBuffer);

  System.out.println("Marking the buffer");

  byteBuffer.mark();
  printStats(byteBuffer);

  System.out.println("Reading next 5 characters from the buffer");
  /* Reading next 5 characters */
  for (int i = 0; i < 5; i++) {
   System.out.println((char) byteBuffer.get());
  }

  printStats(byteBuffer);

  System.out.println("Reseting the buffer");
  byteBuffer.reset();

  printStats(byteBuffer);
 }
}


Output

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


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


Reading first five characters from buffer
a
b
c
d
e
position : 5, limit : 26


Marking the buffer
position : 5, limit : 26


Reading next 5 characters from the buffer
f
g
h
i
j
position : 10, limit : 26


Reseting the buffer
position : 5, limit : 26

By default, mark is set to the value -1. If the mark is defined then it is set back to the value -1, when the position or the limit is adjusted to a value smaller than the mark.

If you call reset method, without marking the buffer, you will end up in ‘java.nio.InvalidMarkException’. My next post, gives you an example of this.




Previous                                                 Next                                                 Home

No comments:

Post a Comment