Java中的ByteBufferplicate()方法
可以使用duplicate()
类java.nio.ByteBuffer中的方法创建缓冲区的重复缓冲区。此重复缓冲区与原始缓冲区相同。该方法duplicate()
返回创建的重复缓冲区。
演示此的程序如下所示-
示例
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 5; try { ByteBuffer buffer1 = ByteBuffer.allocate(5); buffer1.put((byte)1); buffer1.put((byte)2); buffer1.put((byte)3); buffer1.put((byte)4); buffer1.put((byte)5); buffer1.rewind(); System.out.println("The Original ByteBuffer is: " + Arrays.toString(buffer1.array())); ByteBuffer buffer2 = buffer1.duplicate(); System.out.print("The Duplicate ByteBuffer is: " + Arrays.toString(buffer2.array())); } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e) { System.out.println("Error!!! ReadOnlyBufferException"); } } }
输出结果
The Original ByteBuffer is: [1, 2, 3, 4, 5] The Duplicate ByteBuffer is: [1, 2, 3, 4, 5]