Java ByteBuffer convert to String by US-ASCII encoding

Description

Java ByteBuffer convert to String by US-ASCII encoding

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class Main {
  public static void main(String[] argv) {
    ByteBuffer buf = ByteBuffer.wrap("demo2s.com".getBytes());

    String s = null;// w w  w .ja v a2  s . com
    try {
      s = asString(buf);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    System.out.println(s);
  }

  static String asString(final ByteBuffer buffer) throws UnsupportedEncodingException {
    final byte[] bytes = new byte[buffer.limit()];
    buffer.get(bytes);
    return new String(bytes, "US-ASCII");
  }
}



PreviousNext

Related