62,614
社区成员
发帖
与我相关
我的任务
分享
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
public class ByteBufferDemo {
public static void method1(){
Charset utf8 = Charset.forName("UTF-8");
String str = "hello你";
ByteBuffer buf = utf8.encode(str);/// 编码
System.out.println(buf.capacity());// 13
System.out.println(buf.limit());// 8
byte[] info = buf.array();
byte[] newInfo = str.getBytes(utf8);
System.out.println(info.length);// 13
System.out.println(newInfo.length);// 8
System.out.println(Arrays.toString(info));// [104, 101, 108, 108, 111, -28, -67, -96, 0, 0, 0, 0, 0]
System.out.println(Arrays.toString(newInfo));// [104, 101, 108, 108, 111, -28, -67, -96]
System.out.println(new String(info,utf8));// hello你+空字节
System.out.println(new String(newInfo,utf8));// hello你
System.out.println(ByteBuffer.wrap(info).capacity());// 13
System.out.println(ByteBuffer.wrap(info).limit());// 13
}
public static void method2(){
Charset utf8 = Charset.forName("UTF-8");
String str = "hello你好啊啊啊";
ByteBuffer buf = utf8.encode(str);/// 编码
System.out.println(buf.capacity());// 23
System.out.println(buf.limit());// 20
byte[] info = buf.array();
byte[] newInfo = str.getBytes(utf8);
System.out.println(info.length);// 23
System.out.println(newInfo.length);// 20
System.out.println(Arrays.toString(info));// [104, 101, 108, 108, 111, -28, -67, -96, -27, -91, -67, -27, -107, -118, -27, -107, -118, -27, -107, -118, 0, 0, 0]
System.out.println(Arrays.toString(newInfo));// [104, 101, 108, 108, 111, -28, -67, -96, -27, -91, -67, -27, -107, -118, -27, -107, -118, -27, -107, -118]
System.out.println(new String(info,utf8));// hello你好啊啊啊+空字节
System.out.println(new String(newInfo,utf8));// hello你好啊啊啊
System.out.println(ByteBuffer.wrap(info).capacity());// 23
System.out.println(ByteBuffer.wrap(info).limit());// 23
}
public static void main(String[] args) {
method1();
method2();
}
}