Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

ByteBuffer is one of many beneficial classes in the java.nio package. It's used to read data from channels and write data into channels directly.

In this short tutorial, we'll learn how to convert a ByteBuffer to String in Java.

2. Converting a ByteBuffer to String

The process of converting a ByteBuffer to a String is decoding. This process requires a Charset.

There are three ways to convert a ByteBuffer to String:

  • creating a new String from bytebuffer.array()
  • creating a new String from bytebuffer.get(bytes)
  • using charset.decode()

We will use a simple example to showcase all the three ways of converting a ByteBuffer to a String.

3. Practical Example

3.1. Creating a New String From bytebuffer.array()

The first step is to get the byte array from ByteBuffer. To do that, we'll call the ByteBuffer.array() method. This will return the backing array.

Then, we can call the String constructor, which accepts a byte array and character encoding to create our new String:

@Test
public void convertUsingNewStringFromBufferArray_thenOK() {
    String content = "baeldung";
    ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());

    if (byteBuffer.hasArray()) {
        String newContent = new String(byteBuffer.array(), charset);

        assertEquals(content, newContent);
    }
}

3.2. Creating a New String From bytebuffer.get(bytes)

In Java, we can use new String(bytes, charset) to convert a byte[] to a String.

For character data, we can use the UTF_8 charset to convert a byte[] to a String. However, when byte[] is holding non-text binary data, the best practice is to convert the byte[] into a Base64 encoded String:

@Test
public void convertUsingNewStringFromByteBufferGetBytes_thenOK() {
    String content = "baeldung";
    ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());

    byte[] bytes = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytes);
    String newContent = new String(bytes, charset);

    assertEquals(content, newContent);
}

3.3. Using charset.decode()

This is the simplest way to convert a ByteBuffer into a String without any problems:

@Test
public void convertUsingCharsetDecode_thenOK() {
    String content = "baeldung";
    ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes());

    String newContent = charset.decode(byteBuffer).toString();

    assertEquals(content, newContent);
}

4. Conclusion

We have learned in this tutorial three ways to convert ByteBuffer to String in Java. Just remember to use the proper character encoding, and in our example, we used UTF-8.

As always, the complete source code of the examples is available over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!