java 数据流的readInt()怎么判断是否读到了文件尾
假如一个文件里有很多数字,但是具体不知道有多少个,当我们用DataInputStream的readInt()去读取数的时候,有什么最便捷的方法判断是否到了文件的尾部?...
假如一个文件里有很多数字,但是具体不知道有多少个,当我们用DataInputStream的readInt()去读取数的时候,有什么最便捷的方法判断是否到了文件的尾部?
展开
3个回答
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 <= b1, b2, b3, b4 <= 255</code>,
* then the result is equal to:
* <blockquote><pre>
* (b1 << 24) | (b2 << 16) + (b3 << 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));
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
看API最快了
try{
}
catch(EOFException){
}
或者readint返回为空
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,一行一行读取
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |