Java ByteBuffer convert to String by UTF-8

Description

Java ByteBuffer convert to String by UTF-8

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.wrap("demo2s.com".getBytes());
    String a = toTextAll(buf);// www.ja va2s .co  m
    System.out.println(a);
    
  }

  private static final Charset UTF8 = Charset.forName("UTF-8");

  /**
   * Convert whole byte buffer to UTF-8 String.
   *
   * @param bytes Source byte buffer.
   * @return String expression of the bytes.
   */
  public static String toTextAll(ByteBuffer bytes) {
      return new String(bytes.array(), UTF8);
  }
}



PreviousNext

Related