Writing part:

for (int i = 0; i < prices.length; i++) {
    buf.putDouble(prices[i]);
    buf.putInt(units[i]);

    byte[] descsBytes = descs[i].getBytes();
    buf.putInt(descsBytes.length);
    buf.put(descsBytes);
}

Reading part:

while (buf.hasRemaining()) {

    price = buf.getDouble();
    unit = buf.getInt();

    int len = buf.getInt();
    byte[] bytes = new byte[len]; 
    buf.get(bytes);
    desc = new String(bytes);

    System.out.format("You ordered %d" + " units of %s at $%.2f%n",
                unit, desc, price);
    total += unit * price;
}
Answer from user3161880 on Stack Overflow
Discussions

java - Inserting a string into a bytebuffer - Stack Overflow
ByteBuffer has a method for put'ting an array of byte. Is there a reason to put them one at a time? More on stackoverflow.com
🌐 stackoverflow.com
October 7, 2016
java - Why can't I add a String to a ByteBuffer? - Stack Overflow
When I try to add the strings to a bytebuffer, it doesn't write in the file. While I try to add int and double it is working fine. But for strings it doesn't work. buffer.asCharBuffer().put(value.getValue1()); buffer.asCharBuffer().put(value.getValue2()); More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
java - Put a StringBuffer in a ByteBuffer - Stack Overflow
I am trying to put a string buffer in a bytebuffer.. out.put(ss); where out is a ByteBuffer and ss is a StringBuffer. Is there any easy way to do this? Assuming ASCII encoding for the string. Thanks More on stackoverflow.com
🌐 stackoverflow.com
September 22, 2016
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
🌐
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.
🌐
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 ...
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › nio › bytebuffer
Use ByteBuffer to store Strings - Java Code Geeks
March 19, 2019 - Using the put(String) API method we can put a String directly to the byte buffer · The toString() API method returns the string representation of the ByteBuffer’s contents.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › bytebuffer-put-methods-in-java-with-examples-set-1
ByteBuffer put() methods in Java with Examples | Set -1 - GeeksforGeeks
January 19, 2023 - The put(byte b) method of java.nio.ByteBuffer Class is used to write the given byte into the newly created byte buffer at the current position, and then increments the position.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › ByteBuffer.html
ByteBuffer (Java Platform SE 8 )
July 21, 2026 - The buffer's position is set to the number of bytes copied, rather than to zero, so that an invocation of this method can be followed immediately by an invocation of another relative put method. Invoke this method after writing data from a buffer in case the write was incomplete. The following loop, for example, copies bytes from one channel to another via the buffer buf: buf.clear(); // Prepare buffer for use while (in.read(buf) >= 0 || buf.position != 0) { buf.flip(); out.write(buf); buf.compact(); // In case of partial write } ... Tells whether or not this byte buffer is direct. ... Returns a string summarizing the state of this buffer.
🌐
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

🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › nio › ByteBuffer.html
ByteBuffer (Java Platform SE 7 )
The buffer's position is set to the number of bytes copied, rather than to zero, so that an invocation of this method can be followed immediately by an invocation of another relative put method. Invoke this method after writing data from a buffer in case the write was incomplete. The following loop, for example, copies bytes from one channel to another via the buffer buf: buf.clear(); // Prepare buffer for use while (in.read(buf) >= 0 || buf.position != 0) { buf.flip(); out.write(buf); buf.compact(); // In case of partial write } ... Tells whether or not this byte buffer is direct. ... Returns a string summarizing the state of this buffer.
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.

🌐
GeeksforGeeks
geeksforgeeks.org › java › bytebuffer-tostring-method-in-java-with-examples
ByteBuffer toString() method in Java with Examples - GeeksforGeeks
August 6, 2021 - // Java program to demonstrate // toString() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // creating object of ByteBuffer ...
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-understanding-java-bytebuffer-and-converting-it-to-a-string
Java ByteBuffer to String: A Comprehensive Guide - CodingTechRoom
Before converting a ByteBuffer to a String, we need to know what a ByteBuffer is. It is a buffer of bytes that can grow and shrink, providing methods for reading and writing bytes, short, int, and other data types. ... import java.nio.ByteBuffer; // Create a ByteBuffer ByteBuffer byteBuffer = ByteBuffer.allocate(256); byteBuffer.put("Hello, World!".getBytes());
🌐
Onixs
ref.onixs.biz › java-fix-engine-guide › apidocs › biz › onixs › util › ByteBuffer.html
ByteBuffer (Java FIX Engine Package 2.16.2 API)
Appends a single byte to the ByteBuffer. ... Appends the specified byte array to the buffer. ... Appends the content of the provided string to the ByteBuffer using ISO-8859-1 encoding.
🌐
Ymasory
ymasory.github.io › iText-4.2.0 › com › lowagie › text › pdf › ByteBuffer.html
ByteBuffer
Converts the buffer's contents into a string, translating bytes into characters according to the specified character encoding.