import java.io.UnsupportedEncodingException;public class Test { /**
 * @param args
 * @throws UnsupportedEncodingException 
 */
public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
byte[] byteArray = new byte[] {12,-69,63,-126,-1};
int length = 0;
length = byteArray.length;
for (int i = 0; i < length; i++) {
System.out.println("byteArray[" + i + "]=" + byteArray[i]);
}
length = byteArray.length;                  
String str = new String(byteArray, "UTF-8");
System.out.println("str=" + str);
byte b[] = str.getBytes("UTF-8");
int len = b.length;
for (int i = 0; i < len; i++) {
System.out.println("b[" + i + "]=" + b[i]);
}
}
}输出结果 
byteArray[0]=12
byteArray[1]=-69
byteArray[2]=63
byteArray[3]=-126
byteArray[4]=-1
str= �?��
b[0]=12
b[1]=-17
b[2]=-65
b[3]=-67
b[4]=63
b[5]=-17
b[6]=-65
b[7]=-67
b[8]=-17
b[9]=-65
b[10]=-67为什么字节数组不能还原了

解决方案 »

  1.   

    是因为这几个bytes就可能是不对的,{12,-69,63,-126,-1};
    它们不是UTF8的编码,怎么能转对呢?又怎么可能转回来呢?
      

  2.   

    你原来的这个字节数组,是UTF8汉字编码出来的么?如果不是,转String就会丢失,因为找不到对应编码。
      

  3.   

    http://blog.csdn.net/jiakai0419/article/details/7321846如果,你有耐心仔细看这篇文章。你就知道为什么了。如果没什么耐心,那么结合1楼2楼的答案。你也应该能明白一点了。。
      

  4.   

    String str = new String(byteArray, "UTF-8");
    这句不这样用,直接new String(byteArray),第一次转成UTF-8就出错啦
      

  5.   

    以下内容摘自api中关于由字节数组产生字符串的构造函数的说明:
    public String(byte[] bytes,String charsetName);Constructs a new String by decoding the specified array of bytes using the specified charset.The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array. 
      

  6.   

    大哥,你的那个字节数组里面,根本不是UTF-8方式编码的字符。
    你在输出字符串的时候,就已经显示成乱码了。
    既然,你的数据,采用UTF-8方式编码以后,显示的是乱码,那,你的数据必然不是UTF-8方式编码的数据。
    既然,你的数据,不是UTF-8方式编码的数据,那,编码后,再解码,跟定数据会失真,不一致。比如,我给你一篇俄语文章,让你按汉语方式念给大家听,你不认识是吧,但又不能不念,
    那只能胡乱的念出来。这时,我把你念出来的声音记录下来。然后播放给你听,让你在听的时候,
    在用俄语重复写出来(当然,不能让你看到原来的那篇文章)。最后,
    谈谈ISO-8859-1编码的问题,这个编码是西欧字符的编码方式。
    如果,你的数据是西欧字符,那么,恭喜你,你在编码后,能够正常显示,解码的数据也会相同。至于,其他形式的数据,是否也会相同,这要看具体的编码策略,或者说,算法。
    在实际实践中,GBK编码的数据,通过ISO-8859-1方式来编码,再用ISO-8859-1方式解码,
    数据好像不缺损,能够保持一致。