Charset is used to convert ByteBuffer to CharBuffer and
vice versa.
'encode' method of Charset class is used to convert a
CharBuffer to ByteBuffer.
Example
CharBuffer charBuffer = CharBuffer.wrap("Hello
World");
ByteBuffer byteBuffer =
Charset.forName("utf-8").encode(charBuffer);
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 { CharBuffer charBuffer = CharBuffer.wrap("Hello World"); ByteBuffer byteBuffer = Charset.forName("utf-8").encode(charBuffer); for (byte data : byteBuffer.array()) { System.out.print(data + " "); } System.out.println(); } }
Output
72 101 108 108 111 32 87 111 114 108 100 0
No comments:
Post a Comment