BAEL-5147 : convert ByteBuffer to String (#11504)

* BAEL-5147: convert ByteBuffer to String

* Update README.md
This commit is contained in:
ACHRAF TAITAI 2021-11-27 17:59:29 +01:00 committed by GitHub
parent 34d067fa20
commit 3f28be96db
2 changed files with 45 additions and 0 deletions

View File

@ -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)

View File

@ -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);
}
}