Showing posts with label bytebuffer. Show all posts
Showing posts with label bytebuffer. Show all posts

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

Sunday, 16 June 2019

NIO: Convert ByteBuffer to CharBuffer

Charset is used to convert ByteBuffer to CharBuffer and vice versa.

'decode' method of Charset class is used to convert a ByteBuffer to CharBuffer.

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

byteBuffer.flip();
CharBuffer charBuffer = Charset.forName("utf-8").decode(byteBuffer);

Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class Test {

 public static void main(String... args) throws IOException {

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

  byteBuffer.flip();
  CharBuffer charBuffer = Charset.forName("utf-8").decode(byteBuffer);

  System.out.println(charBuffer);
 }
}


Output
Hello World

Previous                                                 Next                                                 Home