2014-09-04 84 views
2

What's的的Java字符串编码

"hello world".getBytes("UTF-8"); 

Charset.forName("UTF-8").encode("hello world").array(); 

区别? 第二个代码在大多数情况下会在末尾产生一个0字节的字节数组。

回答

4

你的第二个片段使用ByteBuffer.array(),它只返回支持ByteBuffer的数组。这可能比编写至ByteBuffer的内容长。

基本上,我想,如果你想使用第一种方法一byte[]String :)你可以与ByteBuffer处理将其转换为一个byte[]使用其他方式,但考虑到String.getBytes(Charset)提供方便,我只是使用...

示例代码从ByteBuffer检索字节:

ByteBuffer buffer = Charset.forName("UTF-8").encode("hello world"); 
byte[] array = new byte[buffer.limit()]; 
buffer.get(array); 
System.out.println(array.length); // 11 
System.out.println(array[0]);  // 104 (encoded 'h') 
+0

只是观察到'字节[] = B1的 “Hello World” .getBytes( “UTF-8” ); byte [] b2 = Charset.forName( “UTF-8”)。encode(“hello world”)。array();'。 'b1.length'打印出11,'b2.length'打印出12个。 – 2014-09-04 16:29:19

+2

@Sandeep:是的,因为'ByteBuffer'大概被分配了长度为12的后备数组。如果你打开'limit()'而不是ByteBuffer,你只会得到11个字节...... – 2014-09-04 16:38:40