Skip to content

Commit 1626a11

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

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package com.baeldung.bytebuffer;
2+
3+
import static org.junit.Assert.assertArrayEquals;
4+
import static org.junit.Assert.assertThrows;
5+
6+
import java.nio.ByteBuffer;
7+
import java.nio.ReadOnlyBufferException;
8+
9+
import org.junit.jupiter.api.Test;
10+
11+
class ByteBufferToByteArrayConversionUnitTest {
12+
13+
@Test
14+
void givenByteBuffer_whenUsingArrayMethod_thenConvertToByteArray() {
15+
byte[] givenBytes = {1, 6, 3};
16+
ByteBuffer buffer = ByteBuffer.wrap(givenBytes);
17+
byte[] bytes = buffer.array();
18+
19+
assertArrayEquals(bytes, givenBytes);
20+
}
21+
22+
@Test
23+
void givenReadOnlyBuffer_whenCallingArray_thenThrowException() {
24+
ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3});
25+
ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
26+
27+
assertThrows(ReadOnlyBufferException.class, readOnlyBuffer::array);
28+
}
29+
30+
@Test
31+
void givenByteBuffer_whenUsingGetMethod_thenConvertToByteArray() {
32+
byte[] givenBytes = {5, 4, 2};
33+
ByteBuffer buffer = ByteBuffer.wrap(givenBytes);
34+
byte[] bytes = new byte[buffer.remaining()];
35+
buffer.get(bytes);
36+
37+
assertArrayEquals(bytes, givenBytes);
38+
}
39+
40+
@Test
41+
void givenByteBuffer_whenUsingGetWithParamsMethod_thenConvertToByteArray() {
42+
byte[] givenBytes = {5, 4, 2, 7};
43+
ByteBuffer buffer = ByteBuffer.wrap(givenBytes);
44+
byte[] bytes = new byte[2];
45+
buffer.get(bytes, 0, 2);
46+
47+
assertArrayEquals(bytes, new byte[] {5, 4});
48+
}
49+
50+
@Test
51+
void givenByteArray_whenUsingWrapMethod_thenConvertToByteBuffer() {
52+
byte[] givenBytes = {1, 2, 3};
53+
ByteBuffer buffer = ByteBuffer.wrap(givenBytes);
54+
55+
assertArrayEquals(buffer.array(), givenBytes);
56+
}
57+
58+
@Test
59+
void givenByteArray_whenUsingWrapWithParamsMethod_thenConvertToByteBuffer() {
60+
byte[] givenBytes = {1, 2, 3, 7, 8};
61+
ByteBuffer buffer = ByteBuffer.wrap(givenBytes, 1, 2);
62+
63+
byte[] actualBytes = new byte[buffer.remaining()];
64+
buffer.get(actualBytes);
65+
66+
assertArrayEquals(actualBytes, new byte[] {2, 3});
67+
}
68+
69+
@Test
70+
void givenByteArray_whenUsingAllocateAndPutMethods_thenConvertToByteBuffer() {
71+
byte[] givenBytes = {1, 9, 7};
72+
ByteBuffer buffer = ByteBuffer.allocate(givenBytes.length);
73+
buffer.put(givenBytes);
74+
75+
assertArrayEquals(buffer.array(), givenBytes);
76+
}
77+
}

0 commit comments

Comments
 (0)