Buffer duplicate() method in Java with Examples
Last Updated :
06 Sep, 2019
The duplicate() method of java.nio.Buffer class is used to create a new buffer that shares this buffer’s content. The content of the new buffer will be that of this buffer. Changes to this buffer’s content will be visible in the new buffer, and vice versa; the two buffers’ position, limit, and mark values will be independent. The new buffer’s capacity, limit, position and mark values will be identical to those of this buffer. The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only.
Syntax:
public abstract Buffer duplicate()
Return Value: This method returns the new buffer which is carrying the previous buffer content.
Below are the examples to illustrate the duplicate() method:
Examples 1: Using direct ByteBuffer
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 4 ;
try {
ByteBuffer bb1
= ByteBuffer.allocate(capacity);
bb1.put(( byte ) 20 );
bb1.put(( byte ) 30 );
bb1.put(( byte ) 40 );
bb1.put(( byte ) 50 );
bb1.rewind();
System.out.println( "Original ByteBuffer: "
+ Arrays.toString(bb1.array()));
ByteBuffer bb2 = bb1.duplicate();
System.out.print( "\nDuplicate ByteBuffer: "
+ Arrays.toString(bb2.array()));
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Original ByteBuffer: [20, 30, 40, 50]
Duplicate ByteBuffer: [20, 30, 40, 50]
Examples 2: Using read-only ByteBuffer
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 4 ;
try {
ByteBuffer bb1
= ByteBuffer.allocate(capacity);
bb1.put(( byte ) 20 );
bb1.put(( byte ) 30 );
bb1.put(( byte ) 40 );
bb1.put(( byte ) 50 );
bb1.rewind();
System.out.println( "Original ByteBuffer: "
+ Arrays.toString(bb1.array()));
ByteBuffer readonly = bb1.asReadOnlyBuffer();
System.out.print( "\nRead-only ByteBuffer: " );
while (readonly.hasRemaining())
System.out.print(readonly.get() + ", " );
System.out.println( "" );
readonly.rewind();
ByteBuffer bb2 = readonly.duplicate();
System.out.print( "\nDuplicate copy of "
+ "read-only ByteBuffer: " );
while (bb2.hasRemaining())
System.out.print(bb2.get() + ", " );
System.out.println( "" );
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Original ByteBuffer: [20, 30, 40, 50]
Read-only ByteBuffer: 20, 30, 40, 50,
Duplicate copy of read-only ByteBuffer: 20, 30, 40, 50,
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#duplicate–
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...