Java Chatset类不明白的地方

niuniu20008 2015-05-05 05:32:42
最近在学习NIO,看的那个头大。学明白一点,过两天又忘了,哎。
闲话少说,Charset有个地方不明白,非常的不明白

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();
}
}


方法1中byte[] info = buf.array();info的长度是13,而newInfo是8?方法2,info的长度是23啊,而newInfo的长度是20.
不懂啊。
...全文
205 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
三仙半 2015-05-06
  • 打赏
  • 举报
回复
ByteBuffer是一个可变长度的字节数组,它的实现原理是先用一个初始容量初始一个字节数组,当增加的内容超过其容量时,再用当前长度和增量长度和新建一个字节数组,然后把原来的内容拷贝过来,再增加新的数据。所以,它有容量大小和实际使用大小。 当调用ByteBuffer的array()方法时,是把它自身管理的字节数组返回,长度是它的当前容量,而从字符串直接转过来的字节数组,是和字符串的长度一致的。
niuniu20008 2015-05-06
  • 打赏
  • 举报
回复
CSDN越来越没人气了,一个帖子发上去,都没人回答。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧