DataInputStream类源码设计错误

    我是一个Java初学者,请各位前辈详解。
    昨天在学习Java 流这部分时候,看jdk源代码,个人感觉sun公司在设计DataOutputStream这个类是不恰当甚至是一个BUG。
    DataInputStream中一个方法readInt(),源代码是
   
public final int readInt() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        int ch3 = in.read();
        int ch4 = in.read();
        if ((ch1 | ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 <<8) + (ch4 << 0));

   }

    其中ch1,ch2,ch3,ch4可能为负数,那样就会抛出异常。

    假入存入的数据为一个正整数,那么ch2<<16 ,ch3 <<8 ,ch4<<0就可能出现负数,如此相加就会出现数据读出的不正确情况。

    这是我的验证移位操作的代码

    byte b = (-1);

    System.out.println(b);

    int i = b;

    i = i << 8;

    System.out.println(i);

    输出结果为 : -1  和  -256

    在DataOutputStream中方法writerInt(),源代码是

    public final void writeInt(int v) throws IOException {

        out.write((v >>> 24) & 0xFF);

        out.write((v >>> 16) & 0xFF);

        out.write((v >>>  8) & 0xFF);

        out.write((v >>>  0) & 0xFF);

        incCount(4);

  }

   两者进行比较我百思不得其解,所以就个人斗胆认为是JDK的源代码出现失误。

   个人建议对readInt()的代码应该修改为如下代码

   public final int readInt() throws IOException {

byte[] b = new byte[4];

for(int i = 0; i<4 ;i++){

b[i] = in.read();

}
        return new BigInteger(b).intValue();

   }

    此外DataInputStream中的readLong(),readShort()等等代码具有这方面的失误。请各位前辈详解,对于一个初学者在这方面是很迷茫的。

    如果对我建议请发邮件给我,我的邮箱为:weizhilee@live.com

    请前辈们原谅在我这里斗胆狂言, 晚生在这里谢谢了。

 

 

有高手替我解决这个问题了,呵呵,我发现原来我错了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值