ByteBuffer reset() in Java

reset(): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

ByteBuffer java.nio.ByteBuffer.reset()

This method resets this buffer's position to the previously marked position.

Parameters: NA

Returns: This buffer.

Exceptions: InvalidMarkException

Approach 1: When no exceptions.

Java

import java.nio.ByteBuffer;

public class ByteBufferreset {
    public static void main(String[] args) {

        byte array[] = { 12345678 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        // set the position
        bb.position(3);

        bb.mark();

        // set new position
        bb.position(6);

        System.out.println("position before reset is " + bb.position());

        bb.reset();

        System.out.println("position after reset is " + bb.position());

    }
}

Output:

position before reset is 6

position after reset is 3


Approach 2: InvalidMarkException

Java

import java.nio.ByteBuffer;

public class ByteBufferreset {
    public static void main(String[] args) {

        byte array[] = { 12345678 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        // set the position
        bb.position(3);

        // set new position
        bb.position(6);

        System.out.println("position before reset is " + bb.position());

        bb.reset();

        System.out.println("position after reset is " + bb.position());

    }
}


Output:

position before reset is 6 Exception in thread "main" java.nio.InvalidMarkException at java.base/java.nio.Buffer.reset(Buffer.java:418) at java.base/java.nio.ByteBuffer.reset(ByteBuffer.java:1408)


No comments:

Post a Comment