将byte数组以UTF-8编码转换为String,再将该String以相同编码转换为byte数组,结果不一样
原byte数组中有两个字符0xD6和0xD0导致转换不一致,怀疑是这两个字符UTF-8编码失败
不知道是否有方法能够实现任意字符的编解码结果一致?源码如下:
import java.io.UnsupportedEncodingException;public class EncodeTester {
public static void main(String[] args)
{
StringBuffer shower = new StringBuffer();

byte[] orgBytes = {0x20,0x20,0x20,(byte)0xD6,(byte)0xD0,0x11,0x22};
for(int i = 0;i < orgBytes.length;++i)
{
shower.append(orgBytes[i]);
if(i != orgBytes.length - 1)
{
shower.append(",");
}
}

System.out.println(shower.toString());

try {
String transferedStr = new String(orgBytes,"UTF-8");

byte[] transBytes = transferedStr.getBytes("UTF-8");
shower = new StringBuffer();
for(int i = 0;i < transBytes.length;++i)
{
shower.append(transBytes[i]);
if(i != transBytes.length-1)
{
shower.append(",");
}
}
System.out.println(shower.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}输出:
32,32,32,-42,-48,17,34
32,32,32,-17,-65,-67,-17,-65,-67,17,34