ByteBuf buf = Unpooled.buffer(10); buf.writeBytes("Hello".getBytes()); ByteBuf copiedBuf = buf.duplicate(); System.out.println("Copied buffer: " + copiedBuf.toString(Charset.defaultCharset()));
ByteBuf buf = Unpooled.wrappedBuffer("Hello World".getBytes()); ByteBuf copiedBuf = buf.duplicate(); //modify the original buffer buf.writeByte('!'); System.out.println("Original buffer: " + buf.toString(Charset.defaultCharset())); System.out.println("Copied buffer: " + copiedBuf.toString(Charset.defaultCharset()));In this example, we create a ByteBuf object "buf" using wrappedBuffer() method, create a new buffer "copiedBuf" using the duplicate() method, write a byte to the original buffer and then print both the original and copied buffer's content. We can see that although we modify the original buffer, the copied buffer remains unchanged. This example also uses the io.netty.buffer package library.