java 数据流的readInt()怎么判断是否读到了文件尾

假如一个文件里有很多数字,但是具体不知道有多少个,当我们用DataInputStream的readInt()去读取数的时候,有什么最便捷的方法判断是否到了文件的尾部?

一般RAF和字节流用int read()读取文件,一次只能读取一个int值的低八位,当读到文件末尾时可以用-1表示,int readInt(),一次读取4个字节,用-1已经不能表示文件末尾了,因为用4个字节可以表示-1,所以用readInt读到文件末尾时,会直接抛异常,即EOFException(end of file),文件到达末尾异常
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-11-28

抛出 EOFException 异常,

以下是源代码 

  /**
     * Reads a signed 32-bit integer from this file. This method reads 4
     * bytes from the file, starting at the current file pointer.
     * If the bytes read, in order, are {@code b1},
     * {@code b2}, {@code b3}, and {@code b4}, where
     * <code>0&nbsp;&lt;=&nbsp;b1, b2, b3, b4&nbsp;&lt;=&nbsp;255</code>,
     * then the result is equal to:
     * <blockquote><pre>
     *     (b1 &lt;&lt; 24) | (b2 &lt;&lt; 16) + (b3 &lt;&lt; 8) + b4
     * </pre></blockquote>
     * <p>
     * This method blocks until the four bytes are read, the end of the
     * stream is detected, or an exception is thrown.
     *
     * @return     the next four bytes of this file, interpreted as an
     *             {@code int}.
     * @exception  EOFException  if this file reaches the end before reading
     *               four bytes.
     * @exception  IOException   if an I/O error occurs.
     */
    public final int readInt() throws IOException {
        int ch1 = this.read();
        int ch2 = this.read();
        int ch3 = this.read();
        int ch4 = this.read();
        if ((ch1 | ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }

第2个回答  2015-11-18
看API最快了
try{
}
catch(EOFException){
}

或者readint返回为空追问

while((num=dis.readInt())!=null)
这种写法失败了呢

追答

试了下感觉怪怪的,read()的是这样的

@return     the total number of bytes read into the buffer, or

     *             <code>-1</code> if there is no more data because the end of

     *             the stream has been reached.

(readint是用read实现的)应该是返回-1,不会涉及EOFException,但实际是抛出的。


有有两个方法:

    直接按照API,用抛出的方法判断

    用Inputstreamreader类实现,直接readline,一行一行读取

本回答被提问者和网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网