日期:2014-05-20  浏览次数:20871 次

String编码问题
我想测试下编码的头,所以,写了些东西,突然,发现点不知所以的问题,前来求教下:
假定"F:/test.txt"中有两个汉字“你好”

public class Test {
private static byte w[] = new byte[1024];
public void readInt() throws IOException{//按照int来读取
System.out.print("Integer info:\t");
FileInputStream fileInS = new FileInputStream("F:/test.txt");//文件中是“你好”
int w = fileInS.read() ;
while( -1 != w ){
System.out.print(w+" ");
w = fileInS.read();
}
System.out.println();
}
public void readByteArray() throws IOException{
System.out.print("ByteArray info:   \t");
FileInputStream fileInS = new FileInputStream("F:/test.txt");//文件中是“你好”
while( -1 != fileInS.read(w) ){
String tmp = toHexDecimal(w);
System.out.print(tmp);
}
System.out.println();
}
private String toHexDecimal(byte... decimal){//将byte[]转型为16进制
byte[] refDecimal = decimal;
StringBuffer sBuf = new StringBuffer();
for( int i=0; i<refDecimal.length ; i++ ){
sBuf.append(Integer.toHexString(refDecimal[i])).append(" ");
}
return sBuf.toString() ;
}


假定:我已经设置默认工程为UTF-8,"F:/test.txt"文件也是UTF-8编码,"F:/test.txt"中有两个汉字“你好”
这两个方法都是UTF-8的,只不过,readInt是按照int来读取,readByteArray是按照byte[],然后输出:

Integer info: 228 189 160 229 165 189 
ByteArray info: ffffffe4 ffffffbd ffffffa0 ffffffe5 ffffffa5 

-----------------问题--------------------
问题1:
仔细观察结果,同一个文件"F:/test.txt"(UTF-8编码的),同样是用UTF-8“读取”,
为什么readInt()读出了6个数字,而readByteArray读出了5个字串?不对等???

问题2:
228 是16进制 0000 00e4,同理189是0000 00bd 。。。
为什么我用readByteArray中用jdk自带的Integer.toHexString(int)却得出ffff ffe4,ffff ffbd等等呢?

求教

------解决方案--------------------
问题1:
我把楼主的代码复制了,运行了一下,也是6个。
问题2:
楼主read之后用byte数组存起来了,就由int变成byte了。
所以就成了Integer.toHexString((byte)228),所以就是ffffffe4。。。
------解决方案--------------------
byte的最大值是127,int的128转为byte就变成了-128,int的228变成byte之后就成-28,byte的-28转为int还是-28,int的-28的16进制就是ffffffe4。