本帖最后由 bgsbati1987 于 2012-01-09 10:46:19 编辑

解决方案 »

  1.   

    readInt方法是获取一个Int类型的数据,具体看方法内部,InputStream的read方法是读取一个字节,Java的int类型是32位的,用InputStream的read方法读取4个字节,然后通过位运算变成一个int数。不知道前面的writeObject的是怎么写的,可能这个int数是你readObject时,需要建立的byte数组的长度吧。
      

  2.   

    我猜是InputStream 前四个字节组成的整数值表示的是整个文件字节数,这个方法是处理特定的文件的读入的吧。
      

  3.   

    是因为在写的时候就定义了这个规则,前面的一个int型表示文件的长度或者什么的,然后读的时候先读出一个int,利用这个值来进行下面的操作~
      

  4.   

    楼主可以测试,推断下结果:
    首先,OutputStream的write(int b)方法很明确的说明:写入的字节是参数 b 的八个低位,b 的 24 个高位将被忽略;也就是说如果b是0-255的数字就不会出现问题,但显然,int是4个字节长度;
    所以OutputStream要想完整的写入一个int值,需要做些处理;其次,InputStream的read()是从输入流中读取数据的下一个字节,注意是一个字节;
    这里需要注意:在流中没有 有符号(一个有符号字节表示范围 -128-127)的概念(但java的byte, short, int, char等基本类型是有符号的),字节都是无符号数字(一个无符号字节表示范围 0-255),但流是用-1来区分是否结束的,显然-1超出了1个无符号字节表示范围,所以返回是个int;楼主看了上面是否清楚了上面代码的做法?简单示例:public static void main(String[] args) throws IOException {
    writeNoProcessedIntValue();
    writeProcessedIntValue();
    } public static void writeNoProcessedIntValue() throws IOException{
    OutputStream out = new FileOutputStream("Text1.bat");
    out.write(100000);
    out.close();

    InputStream in = new FileInputStream("Text1.bat");
    int readByte = in.read();
    in.close();
    System.out.println("No-processed : " + readByte);
    }

    public static void writeProcessedIntValue() throws IOException{
    OutputStream out = new FileOutputStream("Text2.bat");
    out.write(100000>>24);
    out.write(100000>>16);
    out.write(100000>>8);
    out.write(100000>>0);
    out.close();

    InputStream in = new FileInputStream("Text2.bat");
    int readByte1 = in.read();
    int readByte2 = in.read();
    int readByte3 = in.read();
    int readByte4 = in.read();
    in.close();

    System.out.println("Processed : " + ((readByte1 << 24) + (readByte2 << 16) + (readByte3 << 8) + (readByte4 << 0)));
    }
      

  5.   

    readInt()只是从流中读一个整数而已
    至于这个整数为什么刚好是流数据的长度,那取决于发送方和接收方的约定。跟Java本身的API无关。
      

  6.   

    找了下代码writeObject里,它向OutputStream写入了存储对象的长度,而且就是用前四个字节存储的。我原本以为这里的长度是在InputStream中取得的,原来在OutputStream中已经存储了,这里只是读取一下。
      

  7.   

    猜对了,呵呵。原来在之前的OutputStream中用前四个字节中存储了所要存储对象的长度,这里只是读取一下。
      

  8.   

    恩,是这么回事。代码之前在OutputStream中写入了要存储对象的长度,处理的方法正如你所说。PS:讲解的很详细啊,呵呵。
      

  9.   

    是这样的,在OutputStream中,写入了要存储对象的长度。