How to convert ByteBuffer to String in Java

You can easily convert ByteBuffer to String  in Java if you know how to convert byte array to String. Why? because it's very easy to convert ByteBuffer to a byte array and vice versa. 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. Though always remember to provide correct character encoding while converting byte array to String. For example, if you know that ByteBuffer is filled with bytes encoded in UTF-8 then you must use the same encoding while creating String from that byte array. String class provides an overloaded constructor which accepts character encoding along with byte array.  You can use the snippet shared in this example to do the job. ByteBuffer is one of the very useful class in java.nio package which is used to read data from channels and write data into channel directly.

Same ByteBuffer can be used to read and write data. If you want to read from ByteBuffer just call the flip() method and it will convert ByteBuffer into reading mode. In this article, you will learn how to convert ByteBuffer to String in Java. I have a given a simple example, but if you still any doubt you can always leave a comment or question.


ByteBuffer to String in Java - Example

This is one of the simplest examples  to demonstrate how to convert ByteBuffer to String. In this Java program, I have first created a String literal, then I have got the byte array from that String in UTF-8 encoding scheme.


After that, I have created a ByteBuffer object by using same byte array and using ByteBuffer.wrap() method. This is exactly the same situation when your ByteBuffer is filled with data whether you read it from the network or a RandomAccessFile in Java. I have just used this direct approach to create a ByteBuffer with data to simplify this example.

Next part of this program is most important because there we are converting ByteBuffer to String. In order to get the byte array from ByteBuffer just call the ByteBuffer.array() method. This method will return the backed array.

 Now you can call the String constructor which accepts a byte array and character encoding to create String. You are done.

here is our complete code example for converting ByteBuffer to String :


import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;


/**
 * Java Program to convert ByteBuffer to String.
 * It's easy because its similar to how you convert
 * byte array to String. 
 * 
 * @author Javin Paul
 */
public class HelloHP {

    public static void main(String args[]) throws UnsupportedEncodingException {
       
        //Let's first create a ByteBuffer from String
        String content = "It's easy to convert ByteBuffer to String in Java";
        ByteBuffer buffer = ByteBuffer.wrap(content.getBytes("UTF-8"));
       
        // Now let's convert this ByteBuffer to String
        String converted = new String(buffer.array(), "UTF-8");
        
        System.out.println("Original : " + content);
        System.out.println("Converted : " + converted);

    }

}

Output :
Original : It's easy to convert ByteBuffer to String in Java
Converted : It's easy to convert ByteBuffer to String in Java

That's all about how to convert ByteBuffer to String in Java. Just remember to use the right character encoding because without using proper character encoding there is no guarantee that you will get original string back. Though UTF-8 is a good default it cannot be used to provide guaranteed.

ByteBuffer to String in Java with Example


If you like this article and want to learn more about converting one type to another in Java, you can also check following Java tutorials :
  • How to convert float to String in Java? (tutorial)
  • How to convert Double to Long in Java? (tutorial)
  • How to convert Character to String in Java? (tutorial)
  • How to convert String to Int in Java? (example)
  • 5 Ways to convert Java 8 Stream to List? (solution)
  • How to convert SQL date to Util Date in Java? (example)
  • 5 examples of converting InputStream to String in Java? (tutorial)
  • How to convert Enum to String in Java? (guide)
  • How to convert a binary number to decimal in Java? (tutorial)
  • How to convert Array to Set and List in Java? (example)
  • 3 examples of converting Array to ArrayList in Java (tutorial)
  • How to convert String to Enum in Java? (tutorial)
  • How to convert Hexadecimal numbers to octal and binary in Java? (tutorial)
  • The best way to convert Numbers to String in Java? (guide)
  • How to convert java.util.Date to java.sql.Date in Java? (tutorial)
  • How to convert ArrayList to Set in Java? (tutorial)
  • How to convert List to Set in Java? (example)
  • How to convert lowercase String to uppercase in Java? (example)

3 comments:

  1. Not All ByteBuffers are array backed. See the ByteBuffer.hasArray() method and javadocs

    ReplyDelete
    Replies
    1. Indeed, I doubt if direct byte buffer return contents as array. It's better to check hasArray() before calling array() to avoid any problem, but if ByteBuffer is direct then I guess you just can't convert whole ByteBufer to String and that's not practical either. Only option would be to read String line by line or chunk by chunk I guess.

      Delete
  2. Good example,thank you :)

    ReplyDelete