ByteBuf buf = Unpooled.buffer(10); buf.writeBytes(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); // Read slice of length 3, starting from offset 2 ByteBuf slice = buf.readSlice(3).slice(2, 1); // Output: 4 System.out.println(slice.getByte(0));
ByteBuf buf1 = Unpooled.buffer(3).writeBytes(new byte[]{1, 2, 3}); ByteBuf buf2 = Unpooled.buffer(2).writeBytes(new byte[]{4, 5}); // Create composite ByteBuf with two child buffers CompositeByteBuf compositeBuf = Unpooled.compositeBuffer(); compositeBuf.addComponents(true, buf1, buf2); // Read slice of length 2, starting from offset 2 ByteBuf slice = compositeBuf.readSlice(2).slice(2, 1); // Output: 5 System.out.println(slice.getByte(0));In this example, we create two ByteBufs and add them to a composite ByteBuf. We then read a slice of length 2 from the composite buffer, which spans across both child buffers (contains bytes 1, 2, 3, 4, 5), and create a new slice of length 1, starting from offset 2 (which contains byte 5). The java io.netty.buffer package provides a wide range of APIs for handling ByteBufs efficiently.