Saturday 8 June 2019

When will you get InvalidMarkException?


This is continuation to my previous post. If you call the reset() method on buffer instance without marking it, you will end up in this exception.

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.mark();
  byteBuffer.reset();
 }
}

When you ran above application, you will end up in ‘InvalidMarkException’.


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


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


Exception in thread "main" java.nio.InvalidMarkException
 at java.nio.Buffer.reset(Unknown Source)
 at com.sample.nio.Test.main(Test.java:29)

To get rid of the above exception, uncomment the below code.

//byteBuffer.mark();

Previous                                                 Next                                                 Home

No comments:

Post a Comment