为什么此junit测试失败?Java字节[]到/从字符串转换
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字符取两个字节,胜负阵列从在内容和长度传入阵列不同。
请赐教。
尤其是UTF-8不能表示所有字节序列。 – 2013-04-26 08:47:22
谢谢。我非常想将这些字节存储在字符串中。是否有任何支持_any_字节序列的编码,还是我必须用我在上面的junit测试中打印它的方式来表示它? – eirirlar 2013-04-26 08:48:58
尝试ISO-8859-1它将字节转换为字符1到1 – 2013-04-26 08:49:57