Slicing byte arrays in Java
You can use the Arrays.copyOfRange
method. For example:
// slice from index 5 to index 9
byte[] slice = Arrays.copyOfRange(myArray, 5, 10);
The ByteBuffer
you created is being backed by that array. When you call slice()
you effectively receive a specific view of that data:
Creates a new byte buffer whose content is a shared subsequence of this buffer's content.
So calling array()
on that returned ByteBuffer
returns the backing array in its entirety.
To extract all the bytes from that view, you could do:
byte[] bytes = new byte[slicedBuf.remaining()];
slicedBuf.read(bytes);
The bytes from that view would be copied to the new array.
Edit to add from comments below: It's worth noting that if all you're interested in doing is copying bytes from one byte[]
to another byte[]
, there's no reason to use a ByteBuffer
; simply copy the bytes.