There is simpler approach to decode a ByteBuffer into a String without any problems, mentioned by Andy Thomas.

String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
Answer from xinyong Cheng on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java string › convert a bytebuffer to string in java
Convert a ByteBuffer to String in Java | Baeldung
August 15, 2025 - 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:
Discussions

ByteBuffer to String
The String constructor can take a byte array as its initializer. By default it uses the platform-default character encoding which is usually ISO-8859-1. That is fine for simple ASCII stuff but for a "real" system that might talk in multiple languages and what not usually a form of UTF is desired for normalization of data. This stuff matters because bytes have no meaning in and of themselves. Converting them to Strings means interpreting them a certain way. UTF for example might take 4 bytes to make one specific character in its set whereas in ASCII that would probably be interpreted as 4 characters of gibberish. More on reddit.com
🌐 r/java
3
0
April 9, 2013
ByteBuffer to String in Java - Stack Overflow
The decoding creates a CharBuffer which you can conveniently convert to a String. You can reuse the CharSet and it is threadsafe. I wouldn't worry too much about performance (re "fastest way") unless you have really a problem in that area. A general advice, when you want to use ByteBuffer, do the ... More on stackoverflow.com
🌐 stackoverflow.com
April 5, 2017
arrays - Convert ByteBuffer to String in Java - Stack Overflow
But you should really be using a Charset decoder to yield a CharBuffer for this. At least you should specify a character set to the String constructor. ... You create it, call CharsetDecoder.decode(ByteBuffer) to produce a CharBuffer, then turn that directly into a String. More on stackoverflow.com
🌐 stackoverflow.com
July 20, 2016
Java: Converting String to and from ByteBuffer and associated problems - Stack Overflow
I am using Java NIO for my socket connections, and my protocol is text based, so I need to be able to convert Strings to ByteBuffers before writing them to the SocketChannel, and convert the incoming More on stackoverflow.com
🌐 stackoverflow.com
🌐
Java67
java67.com › 2015 › 06 › how-to-convert-bytebuffer-to-string-in-java-example.html
How to convert ByteBuffer to String in Java [Example] | Java67
All you need to do is call the ByteBuffer.array() method, it will return you the byte array used by java.nio.ByteBuffer class, later you can easily create String from that byte array.
🌐
Reddit
reddit.com › r/java › bytebuffer to string
r/java on Reddit: ByteBuffer to String
April 9, 2013 -

Hi Guys,

Could anyone please tell me how I can convert a ByteBuffer to a String? I thought it would be a simple function but I can't seem to work it out.

This is just a part of what I have written. I am essentially trying to read a message sent via TCP. There were intermediate steps which I didn't think were necessary to include here.

ServerSocketChannel tcpserver = ServerSocketChannel.open();
SocketChannel connectionSocket = tcpserver.accept();

// create buffer to hold message
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = connectionSocket.read(buf);

While googling around, there was talk of paying attention to character encoding. Could someone please explain how this factors into the problem at hand?

Any help would be greatly appreciated!!

Kind Regards,

Giri

🌐
GeeksforGeeks
geeksforgeeks.org › java › bytebuffer-tostring-method-in-java-with-examples
ByteBuffer toString() method in Java with Examples - GeeksforGeeks
August 6, 2021 - The toString() method of ByteBuffer class is the inbuilt method used to returns a string representing the data contained by ByteBuffer Object. A new String object is created and initialized to get the character sequence from this ByteBuffer ...
Top answer
1 of 2
7

A way to convert a ByteBuffer to a String would be to use a Charset to decode the bytes:

Charset charset = Charset.forName("ISO-8859-1");

ByteBuffer m_buffer = ...;

String text = charset.decode(m_buffer).toString();

The decoding creates a CharBuffer which you can conveniently convert to a String. You can reuse the CharSet and it is threadsafe. I wouldn't worry too much about performance (re "fastest way") unless you have really a problem in that area. A general advice, when you want to use ByteBuffer, do the to-String conversion as late as possible, and only when the String is needed.

As 14jbella mentioned, Strings are immutable. There is no way of creating a String from an array (char or byte) that does not include copying the data because arrays are mutable. So no, there is no way to do it without copying.

Further you should take into consideration, that m_buffer.array() returns the internal array of the ByteBuffer, which may be much more than the actual data stored in the buffer. Creating a String from that array might lead to a potentially huge memory allocation, because the data gets copied into a new array. For example if you're using a 256 MB ByteBuffer somewhere in your code, and you get a slice() of 32 bytes named m_buffer from that buffer to convert to a String, your invocation of new String(m_buffer.array()) would allocate a new byte array of the size of the original, backing byte array, which is 256 MB, which is probably not that fast, if it requires a GC.

Btw. new String(byte[]) internally uses a CharSet decoder on a ByteBuffer wrapped around your input byte array.

2 of 2
4

Java's String class is immutable. In order to maintain this guarantee, String has to have its own reference to the char[] backing it, and nobody else may have that reference. If it were to share an array with the ByteBuffer, the String class could not guarantee that it would not be modified. In addition, char, and byte are not the same in Java.

Top answer
1 of 4
12

You need to use the buffer's position and limit to determine the number of bytes to read.

// ...populate the buffer...
buffer.flip(); // flip the buffer for reading
byte[] bytes = new byte[buffer.remaining()]; // create a byte array the length of the number of bytes written to the buffer
buffer.get(bytes); // read the bytes that were written
String packet = new String(bytes);

In my opinion you shouldn't really be using the backing array() at all; it's bad practice. Direct byte buffers (created by ByteBuffer.allocateDirect() won't have a backing array and will throw an exception when you try to call ByteBuffer.array(). Because of this, for portability you should try to stick to the standard buffer get and put methods. Of course, if you really want to use the array you can use ByteBuffer.hasArray() to check if the buffer has a backing array.

2 of 4
1

The answer talking about setting range from position to limit is not correct in a general case. When the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):

if (myByteBuffer.hasArray()) {
    return new String(myByteBuffer.array(),
        myByteBuffer.arrayOffset() + myByteBuffer.position(),
        myByteBuffer.remaining());
} else {
    final byte[] b = new byte[myByteBuffer.remaining()];
    myByteBuffer.duplicate().get(b);
    return new String(b);
}

For the concerns related to encoding, see Andy Thomas' answer.

Find elsewhere
🌐
Codemia
codemia.io › knowledge-hub › path › java_bytebuffer_to_string
Java ByteBuffer to String
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
Top answer
1 of 3
56

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

2 of 3
55

Unless things have changed, you're better off with

public static ByteBuffer str_to_bb(String msg, Charset charset){
    return ByteBuffer.wrap(msg.getBytes(charset));
}

public static String bb_to_str(ByteBuffer buffer, Charset charset){
    byte[] bytes;
    if(buffer.hasArray()) {
        bytes = buffer.array();
    } else {
        bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
    }
    return new String(bytes, charset);
}

Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.

🌐
GitHub
gist.github.com › qingniufly › 9d976136d908f1e52a1b69b40449565b
Java NIO, ByteBuffer <--> String - Gist - GitHub
Save qingniufly/9d976136d908f1e52a1b69b40449565b to your computer and use it in GitHub Desktop. Download ZIP · Java NIO, ByteBuffer <--> String · Raw · ByteBufferConverter.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
GitHub
gist.github.com › 10b8a74d64df9c6f29f1
Byte buffer to string · GitHub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-understanding-java-bytebuffer-and-converting-it-to-a-string
Java ByteBuffer to String: A Comprehensive Guide - CodingTechRoom
To convert a ByteBuffer to a String, we will use the `StandardCharsets` class for character encoding and then obtain a byte array from the ByteBuffer.
🌐
Baeldung
baeldung.com › home › java › java string › convert string to byte array and reverse in java
Convert String to Byte Array and Reverse in Java | Baeldung
March 17, 2024 - So far, we have converted a byte array into a String using the constructor, and now we’ll look into the other approaches. The Charset class provides the decode() method that converts a ByteBuffer to String:
🌐
GitHub
gist.github.com › reddikih › 00ed63847f9f4e620e9d4772d69cbee5
java convert bytebuffer to string · GitHub
java convert bytebuffer to string. GitHub Gist: instantly share code, notes, and snippets.
🌐
GitHub
gist.github.com › 9d976136d908f1e52a1b69b40449565b
Java NIO, ByteBuffer <--> String · GitHub
Save qingniufly/9d976136d908f1e52a1b69b40449565b to your computer and use it in GitHub Desktop. Download ZIP · Java NIO, ByteBuffer <--> String · Raw · ByteBufferConverter.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › nio › bytebuffer
Use ByteBuffer to store Strings - Java Code Geeks
March 19, 2019 - The toString() API method returns the string representation of the ByteBuffer’s contents.
🌐
Protocol Buffers
protobuf.dev › reference › java › api-docs › com › google › protobuf › ByteString
ByteString
Immutable sequence of bytes. Provides conversions to and from byte[], String, ByteBuffer, InputStream, OutputStream.