Java String convert from ByteBuffer by UTF-8

Description

Java String convert from ByteBuffer by UTF-8


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

public class Main {
  public static void main(String[] argv) {
    ByteBuffer b = ByteBuffer.wrap("demo2s.com".getBytes());
    //from w  ww  .j a v  a 2  s .c om
    String s = stringFromBuffer(b);
    System.out.println(s);
  }
  /**
   *  Convert the content of a byte buffer to a string, using a
   *  default char encoding
   *  @param buf is the byte buffer
   *  @return a string
   */
  public static String stringFromBuffer(ByteBuffer buf) {
      Charset charset = Charset.forName("UTF-8");
      return (stringFromBuffer(buf, charset));
  }
  /**
   * Convert the content of a byte buffer to a string
   * 
   * @param buf
   *          is the byte buffer
   * @param charset
   *          indicates the character set encoding
   * @return a string
   */
  public static String stringFromBuffer(ByteBuffer buf, Charset charset) {
    CharBuffer cb = charset.decode(buf.duplicate());
    return (cb.toString());
  }

}



PreviousNext

Related