diff --git a/core-java-modules/core-java-string-conversions-2/README.md b/core-java-modules/core-java-string-conversions-2/README.md index 46eb783a27..22f4cd89a1 100644 --- a/core-java-modules/core-java-string-conversions-2/README.md +++ b/core-java-modules/core-java-string-conversions-2/README.md @@ -9,4 +9,5 @@ This module contains articles about string conversions from/to another type. - [Converting String to BigDecimal in Java](https://www.baeldung.com/java-string-to-bigdecimal) - [Converting String to BigInteger in Java](https://www.baeldung.com/java-string-to-biginteger) - [Convert a String to Camel Case](https://www.baeldung.com/java-string-to-camel-case) +- [Convert a ByteBuffer to String] - More articles: [[<-- prev]](/core-java-string-conversions) diff --git a/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java b/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java new file mode 100644 index 0000000000..c498921d9a --- /dev/null +++ b/core-java-modules/core-java-string-conversions-2/src/test/java/com/baeldung/bytebuffertostring/ByteArrayToStringUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.bytebuffertostring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +public class ByteArrayToStringUnitTest { + private static Charset charset = StandardCharsets.UTF_8; + private static final String content = "baeldung"; + + @Test + public void convertUsingNewStringFromBufferArray_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + if (byteBuffer.hasArray()) { + String newContent = new String(byteBuffer.array(), charset); + assertEquals(content, newContent); + } + } + + @Test + public void convertUsingNewStringFromByteBufferGetBytes_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + byte[] bytes = new byte[byteBuffer.remaining()]; + byteBuffer.get(bytes); + String newContent = new String(bytes, charset); + assertEquals(content, newContent); + } + + @Test + public void convertUsingCharsetDecode_thenOK() { + // Allocate a ByteBuffer + ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes()); + String newContent = charset.decode(byteBuffer) + .toString(); + assertEquals(content, newContent); + } + +}