java byte转换成string_Java byte []到/从String转换
為什么這個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
總結
以上是生活随笔為你收集整理的java byte转换成string_Java byte []到/从String转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 404未找到是什么意思_http404未
- 下一篇: html中header标签怎么用