Java-Mark and Reset

Mark and Reset

Mark allows a buffer to remember a position and return to it later. A buffer’s mark is undefined until the mark( ) method is called, at which time the mark is set to the current position. The reset( ) method sets the position to the current mark. If the mark is undefined, calling reset( ) will result in an InvalidMarkException. Some buffer methods will discard the mark if one is set ( rewind( ), clear( ), and flip( ) always discard the mark). Calling the versions of limit( ) or position( ) that take index arguments will discard the mark if the new value being set is less than the current mark. Let’s see how this works. Executing the code buf.mark( );  mark is set to the current position. Results in the buffer state shown in following figure :

If you read this buffer, bytes 60,70,80,90,100 would be returned and the position would advance to 10.

If we then call reset( ), the position would be set to the mark as shown in following figure :

Reading the buffer again would result in five bytes 60,70,80,90,100 being returned.

Program

output1

Program Source

import java.nio.ByteBuffer;

public class Javaapp {

    public static void main(String[] args) {

        ByteBuffer buf = ByteBuffer.allocate(12);
        buf.put(new byte[]{10,20,30,40,50,60,70,80,90,100});
        buf.flip();
        for(int i=0;i<5;i++)
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
        buf.mark();
        while(buf.hasRemaining())
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
        System.out.println();
        buf.reset();
        while(buf.hasRemaining())
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
    }
}

Leave a Comment