Monday, 13 December 2021

Java: Convert string to ByteBuffer

Below snippet is used to convert string to a ByteBuffer.

ByteBuffer byteBuffer = ByteBuffer.allocate(100);
byteBuffer.put("Hello World".getBytes(StandardCharsets.UTF_8));

Find the below working application.

 

StringToByteBuffer.java

package com.sample.app.strings;

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

public class StringToByteBuffer {

	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



Previous                                                    Next                                                    Home

No comments:

Post a Comment