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

No comments:

Post a Comment