The documentation for the ByteBuffer class specifies that the getInt() method reads the next four bytes, so if you are only passing two bytes to the call to wrap, you will get a BufferUnderflowException:
Answer from andersschuller on Stack OverflowThrows: BufferUnderflowException - If there are fewer than four bytes remaining in this buffer
I would hope you mean byte[] not Byte[]
A put() is the fastest way to copy a byte[] into a ByteBuffer. An even faster way is to write into the ByteBuffer in the first place and not use a byte[] at all.
If the copy is taking 100ms, perhaps you are copying too much data. In this test it copies 1 MB in 128 micro-seconds.
ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024);
byte[] bytes = new byte[bb.capacity()];
int runs = 50000;
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
bb.clear();
bb.put(bytes);
}
long time = System.nanoTime() - start;
System.out.printf("Average time to copy 1 MB was %.1f us%n", time / runs / 1e3);
prints
Average time to copy 1 MB was 128.9 us
wrap should be much faster, as --if I understand the doc correctly-- it does not copy the byte array, but just sets the member variables (capacity/limit/position). wrap only makes sense, if you already got the byte[] with the desired data from somewhere, of course.
That is the expected result.
According to the JavaDoc from ByteBuffer.wrap():
Wraps a byte array into a buffer.
The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa.
And ByteBuffer.array():
Returns the byte array that backs this buffer (optional operation).
Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa.
That means that ByteBuffer.array() will return the very same array that you wrapped with ByteBuffer.wrap().
array() returns the byte array that backs the buffer.
It's the same object. i.e. byteBuf.array() == data
To construct a string with subarray of data, use:
String msg = new String(data, 0, 15);