String编码问题

weidu23 2014-01-22 12:03:58
我想测试下编码的头,所以,写了些东西,突然,发现点不知所以的问题,前来求教下:
假定"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等等呢?

求教
...全文
227 4 打赏 收藏 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
weidu23 2014-01-23
  • 打赏
  • 举报
回复
引用 3 楼 duxingzhe0311 的回复:
byte的最大值是127,int的128转为byte就变成了-128,int的228变成byte之后就成-28,byte的-28转为int还是-28,int的-28的16进制就是ffffffe4。
谢了
rockets311 2014-01-22
  • 打赏
  • 举报
回复
byte的最大值是127,int的128转为byte就变成了-128,int的228变成byte之后就成-28,byte的-28转为int还是-28,int的-28的16进制就是ffffffe4。
weidu23 2014-01-22
  • 打赏
  • 举报
回复
引用 1 楼 duxingzhe0311 的回复:
问题1: 我把楼主的代码复制了,运行了一下,也是6个。 问题2: 楼主read之后用byte数组存起来了,就由int变成byte了。 所以就成了Integer.toHexString((byte)228),所以就是ffffffe4。。。
问题1:我回去再试试 问题2:(byte)228是(byte)((int)228),也就是说,byte是截断了高位! 那么,截断了就应该没了啊?怎么反倒数值变得非常的大了 ???
rockets311 2014-01-22
  • 打赏
  • 举报
回复
问题1: 我把楼主的代码复制了,运行了一下,也是6个。 问题2: 楼主read之后用byte数组存起来了,就由int变成byte了。 所以就成了Integer.toHexString((byte)228),所以就是ffffffe4。。。

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧