如何查看 Reader 是否处于 EOF?
我的代码需要读入整个文件。目前我正在使用以下代码:
BufferedReader r = new BufferedReader(new FileReader(myFile));
while (r.ready()) {
String s = r.readLine();
// do something with s
}
r.close();
但是,如果文件当前为空,则 s
为 null,这不好。是否有任何 Reader
具有 atEOF()
方法或等效方法?
My code needs to read in all of a file. Currently I'm using the following code:
BufferedReader r = new BufferedReader(new FileReader(myFile));
while (r.ready()) {
String s = r.readLine();
// do something with s
}
r.close();
If the file is currently empty, though, then s
is null, which is no good. Is there any Reader
that has an atEOF()
method or equivalent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
文档 说:
< em>
public int read() 抛出 IOException
返回:
读取的字符为 0 到 65535 (0x00-0xffff) 范围内的整数,如果已到达流末尾,则为 -1。
因此,在 Reader 的情况下,应检查 EOF,如
In对于 BufferedReader 和 readLine() 的情况,可能是
因为 readLine() 在 EOF 上返回 null。
The docs say:
public int read() throws IOException
Returns:
The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached.
So in the case of a Reader one should check against EOF like
In the case of a BufferedReader and readLine(), it may be
because readLine() returns null on EOF.
使用这个函数:
Use this function:
您想要做的事情的标准模式是:
A standard pattern for what you are trying to do is:
Ready() 方法将不起作用。您必须从流中读取并检查返回值以查看是否位于 EOF。
the ready() method will not work. You must read from the stream and check the return value to see if you are at EOF.