Java-Rewind and Clear

Rewind and Clear

The rewind( ) method is similar to flip( ) but does not affect the limit. It only sets the position back to 0. You can use rewind( ) to go back and reread the data in a buffer that has already been flipped.

Once a buffer has been filled and readed, it can be reused. The clear( ) method resets a buffer to an empty state. It doesn’t change any of the data elements of the buffer but simply sets the limit to the capacity and the position back to 0.

Rewind Example

output1

Clear Example

output2Program 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();
        while(buf.hasRemaining())
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
        buf.rewind();
        System.out.println();
        while(buf.hasRemaining())
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
    }
}

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();
        while(buf.hasRemaining())
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
        buf.clear();
        buf.put(new byte[]{5,10,15,20,25,30,35,40,45,50});
        buf.flip();
        System.out.println();
        while(buf.hasRemaining())
        {
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");
        }
    }
}

Leave a Comment