Java Charset.encode(CharBuffer cb)

Syntax

Charset.encode(CharBuffer cb) has the following syntax.

public final ByteBuffer encode(CharBuffer cb)

Example

In the following code shows how to use Charset.encode(CharBuffer cb) method.


import java.nio.ByteBuffer;
import java.nio.charset.Charset;
/*from ww w  .ja  v a2  s.  c o  m*/
public class Main {

  public static void print(ByteBuffer bb) {
    while (bb.hasRemaining())
      System.out.print(bb.get() + " ");
    System.out.println();
    bb.rewind();
  }

  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { (byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'2', (byte) 's' });
    print(bb);
    Charset csets = Charset.forName("UTF-16LE");

    System.out.println(csets.name() + ":");
    print(csets.encode(bb.asCharBuffer()));
    csets.decode(bb);
    bb.rewind();

  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    java.nio.charset »




Charset
CharsetDecoder
CharsetEncoder
StandardCharsets