Java-View Buffer

View Buffer

Buffers can manage data stored in other buffers. When you create a buffer that manages another buffer’s data, the created buffer is known as view buffer. Changes made in either buffer are reflected in the other. View buffers are created by calling a Buffer subclass’s duplicate( ) method. The resulting view buffer is equivalent to the original buffer; both buffers share the same data items and have equivalent capacities. However, each buffer has its own position, limit, and mark. Consider the following example :

The ByteBuffer instance identified by viewbuf shares the same internal array of 12 elements as buf. At the moment, these buffers have the same position, limit, and capacity. However, these properties in one buffer can be changed independently of the properties in the other buffer.

You can make a read-only view of a buffer with the asReadOnlyBuffer( ) method. This is the same as duplicate( ), except that the new buffer will disallow put( )s, and its isReadOnly( ) method will return true. Attempting a call to put( ) on the read-only buffer will throw a ReadOnlyBufferException.



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});
        ByteBuffer viewbuf = buf.duplicate();
            System.out.print("["+viewbuf.position()+"-"+viewbuf.get()+"] ");
        viewbuf.put(new byte[]{110,115,120,125});
            System.out.print("["+buf.position()+"-"+buf.get()+"] ");

Leave a Comment