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 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:
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
Btw. new String(byte[]) internally uses a CharSet decoder on a ByteBuffer wrapped around your input byte array. ... Sign up to request clarification or add additional context in comments. ... Java's String class is immutable. In order to maintain this guarantee, String has to have its own reference ... 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
In this Java program, I have first created a String literal, then I have got the byte array from that String in the UTF-8 encoding scheme. After that, I have created a ByteBuffer object by using the same byte array and using ByteBuffer.wrap() method.
🌐
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

🌐
Blogger
self-learning-java-tutorial.blogspot.com › 2021 › 12 › java-convert-bytebuffer-to-string.html
Programming for beginners: Java: Convert ByteBuffer to a string
JavaScript · Julia · Kotlin · Nexus · Node.js · Prolog Tutorial · Python · R Tutorial for beginners · Spring Framework · XML · YAML · Approach 1: 'StandardCharsets.UTF_8.decode(byteBuffer).toString()' method can be used to convert ByteBuffer to a string.
🌐
GeeksforGeeks
geeksforgeeks.org › java › bytebuffer-tostring-method-in-java-with-examples
ByteBuffer toString() method in Java with Examples - GeeksforGeeks
August 6, 2021 - Java Collection · Last Updated : 6 Aug, 2021 · The toString() method of ByteBuffer class is the inbuilt method used to returns a string representing the data contained by ByteBuffer Object.
🌐
GitHub
gist.github.com › reddikih › 00ed63847f9f4e620e9d4772d69cbee5
java convert bytebuffer 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.
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 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.

🌐
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.
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.

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.

🌐
CodingTechRoom
codingtechroom.com › tutorial › java-java-bytebuffer-to-string
Java ByteBuffer to String: A Comprehensive Guide - CodingTechRoom
In this tutorial, we will explore how to convert a Java `ByteBuffer` to a `String`, an essential task when dealing with byte data in applications such as network programming, I/O operations, and data manipulation.
🌐
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.
🌐
YouTube
youtube.com › watch
java bytebuffer to string - YouTube
Get Free GPT4.1 from https://codegive.com/a2f1a11## Java ByteBuffer to String: A Comprehensive GuideByteBuffer is a fundamental class in Java's NIO (New Inp...
Published: June 26, 2025
🌐
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. Do not forget to flip() the ByteBuffer since the toString() API method displays ByteBuffer’s contents from the current buffer’s position on-wards ...
🌐
Protocol Buffers
protobuf.dev › reference › java › api-docs › com › google › protobuf › ByteString
ByteString
Similar to String.endsWith(String) ... true if the byte sequence represented by the argument is a suffix of the byte sequence represented by this string; false otherwise. public static ByteString copyFrom(byte[] bytes, int offset, int size) Copies the given bytes into a ByteString. ... Copies the given bytes into a ByteString. ... Copies the next size bytes from a java.nio.ByteBuffer into a ByteString.
🌐
Coderanch
coderanch.com › t › 327670 › java › java-nio-ByteBuffer-StringBuffer
java.nio.ByteBuffer to StringBuffer (Java in General forum at Coderanch)
Convert java.nio.ByteBuffer object to a StringBuffer. But, when I print the contents of StringBuffer using SOP, it prints a series of '?'.