为什么这个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);
}
}
我假设传入的字节数组等于结果,但不知何故,可能是因为UTF-8字符占用两个字节,结果数组在内容和长度上都与传入数组不同.
请赐教.
解决方法:
原因是0,-121,-80,116,-62不是有效的UTF-8字节序列. new String(bytes,“UTF-8”)在这种情况下不会抛出任何异常,但结果很难预测.读取http://en.wikipedia.org/wiki/UTF-8无效的字节序列部分.
标签:java,bytearray,utf-8,byte,string
来源: https://codeday.me/bug/20190520/1142670.html