爲什麼此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