eir*_*lar 5 java string byte bytearray utf-8
为什么这个junit测试失败了?
import org.junit.Assert;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
public class TestBytes {
@Test
public void testBytes() throws UnsupportedEncodingException {
byte[] bytes = new byte[]{0, -121, -80, 116, -62};
String string = new String(bytes, "UTF-8");
byte[] bytes2 = string.getBytes("UTF-8");
System.out.print("bytes2: [");
for (byte b : bytes2) System.out.print(b + ", ");
System.out.print("]\n");
Assert.assertArrayEquals(bytes, bytes2);
}
}
Run Code Online (Sandbox Code Playgroud)
我假设传入的字节数组等于结果,但不知何故,可能是因为UTF-8字符占用两个字节,结果数组在内容和长度上都与传入数组不同.
请赐教.
原因是0, -121, -80, 116, -62不是有效的 UTF-8 字节序列。new String(bytes, "UTF-8") 在这种情况下不会抛出任何异常,但结果很难预测。阅读http://en.wikipedia.org/wiki/UTF-8 无效字节序列部分。
| 归档时间: |
|
| 查看次数: |
1164 次 |
| 最近记录: |