Skip to content

Commit 0e520d0

Browse files
committed
BAEL-8276: Convert Between ByteBuffer and Byte Array in Java
1 parent 6c75a16 commit 0e520d0

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.bytebuffer;
2+
3+
import static org.junit.Assert.assertArrayEquals;
4+
5+
import java.nio.ByteBuffer;
6+
7+
import org.junit.jupiter.api.Test;
8+
9+
class ByteBufferToByteArrayConversionUnitTest {
10+
11+
@Test
12+
void whenUsingArrayMethod_thenConvertToByteArray() {
13+
byte[] givenBytes = {1, 6, 3};
14+
ByteBuffer buffer = ByteBuffer.wrap(givenBytes);
15+
byte[] bytes = buffer.array();
16+
17+
assertArrayEquals(bytes, givenBytes);
18+
}
19+
20+
@Test
21+
void whenUsingGetMethod_thenConvertToByteArray() {
22+
byte[] givenBytes = {5, 4, 2};
23+
ByteBuffer buffer = ByteBuffer.wrap(givenBytes);
24+
byte[] bytes = new byte[buffer.remaining()];
25+
buffer.get(bytes);
26+
27+
assertArrayEquals(bytes, givenBytes);
28+
}
29+
30+
@Test
31+
void whenUsingWrapMethod_thenConvertToByteBuffer() {
32+
byte[] givenBytes = {1, 2, 3};
33+
ByteBuffer buffer = ByteBuffer.wrap(givenBytes);
34+
35+
assertArrayEquals(buffer.array(), givenBytes);
36+
}
37+
38+
@Test
39+
void whenUsingAllocateAndPutMethods_thenConvertToByteBuffer() {
40+
byte[] givenBytes = {1, 9, 7};
41+
ByteBuffer buffer = ByteBuffer.allocate(givenBytes.length);
42+
buffer.put(givenBytes);
43+
44+
assertArrayEquals(buffer.array(), givenBytes);
45+
}
46+
}

0 commit comments

Comments
 (0)