Java-Slice Buffer

Slice Buffer

Slicing a buffer is similar to duplicating, but slice( ) creates a new buffer that starts at the original buffer’s current position and whose capacity is the number of elements remaining in the original buffer (limit – position). The new buffer shares a subsequence of the data elements of the original buffer. The slice buffer will also inherit read-only attribute. Following figure illustrates the slicing buffer :

Program

output

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();
        buf.position(5);
        ByteBuffer getbuf = buf.slice();
        while(getbuf.hasRemaining())
        {
            System.out.print("["+getbuf.position()+"-"+getbuf.get()+"] ");
        }
    }
}

Leave a Comment