Java Buffer rewind()

PreviousNext

The rewind() method of java.nio.ByteBuffer Class rewinds this buffer.

The position is set to zero and the mark is discarded.

Syntax:

public ByteBuffer rewind()

Return Value: This method returns this buffer.

Example

The following code shows how to use Buffer rewind() method:

import java.nio.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // defining and allocating ByteBuffer
        // using allocate() method
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);

        // put byte value in byteBuffer
        // using put() method
        byteBuffer.put((byte) 20);
        byteBuffer.put((byte) 'a');

        // Typecast Bytebuffer to buffer
        Buffer buffer = (Buffer) byteBuffer;

        // print the byte buffer
        System.out.println("Buffer before operation: " + Arrays.toString((byte[]) buffer.array()) + "\nPosition: "
                + buffer.position() + "\nLimit: " + buffer.limit());

        // rewind the Buffer
        // using rewind() method
        buffer.rewind();/* w  w  w  .  d   e m o   2 s  .  c   o   m*/

        // print the bytebuffer
        System.out.println("\nBuffer after operation: " + Arrays.toString((byte[]) buffer.array()) + "\nPosition: "
                + buffer.position() + "\nLimit: " + buffer.limit());
    }
}

Result

Examples 2:

Java program to demonstrate rewind() method

import java.nio.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        // defining and allocating ByteBuffer
        // using allocate() method
        ByteBuffer byteBuffer = ByteBuffer.allocate(5);

        // put byte value in byteBuffer
        // using put() method
        byteBuffer.put((byte) 20);
        byteBuffer.put((byte) 30);
        byteBuffer.put((byte) 40);

        // mark will be going to discard
        // by rewind()
        byteBuffer.mark();/* w  w   w .   d  e m o  2    s  .  c  o  m*/

        // Typecast Bytebuffer to buffer
        Buffer buffer = (Buffer) byteBuffer;

        // print the buffer
        System.out.println("Buffer before operation: " + Arrays.toString((byte[]) buffer.array()) + "\nPosition: "
                + buffer.position() + "\nLimit: " + buffer.limit());

        // rewind the Buffer
        // using rewind() method
        buffer.rewind();

        // print the bytebuffer
        System.out.println("\nBuffer after operation: " + Arrays.toString((byte[]) buffer.array()) + "\nPosition: "
                + buffer.position() + "\nLimit: " + buffer.limit());
    }
}

Result

PreviousNext

Related