BAEL-5147 : convert ByteBuffer to String (#11504)
* BAEL-5147: convert ByteBuffer to String * Update README.md
This commit is contained in:
parent
34d067fa20
commit
3f28be96db
|
@ -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)
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue