Monday 13 December 2021

Java: Convert ByteBuffer to a string

Approach 1: 'StandardCharsets.UTF_8.decode(byteBuffer).toString()' method can be used to convert ByteBuffer to a string.

 

ByteBufferToString.java

package com.sample.app.strings;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class ByteBufferToString {

	public static void main(String args[]) {
		ByteBuffer byteBuffer = ByteBuffer.allocate(100);
		byteBuffer.put("Hello World".getBytes(StandardCharsets.UTF_8));

		byteBuffer.flip();
		String str = StandardCharsets.UTF_8.decode(byteBuffer).toString();

		System.out.println("str : " + str);
	}

}

Output

str : Hello World

 

Approach 2: Get the bytes from ByteBuffer and convert the bytes to a string.

byte[] bytes = byteBuffer.array();
String str = new String(bytes, StandardCharsets.UTF_8);

ByteBufferToString1.java

package com.sample.app.strings;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class ByteBufferToString1 {

	public static void main(String args[]) {
		ByteBuffer byteBuffer = ByteBuffer.allocate(100);
		byteBuffer.put("Hello World".getBytes(StandardCharsets.UTF_8));

		byte[] bytes = byteBuffer.array();
		String str = new String(bytes, StandardCharsets.UTF_8);

		System.out.println("str : " + str);

	}

}

Output

str : Hello World

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment