This is continuation to my previous post. If you call the reset() method on the 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’.
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here