Java 如何查看 Reader 是否处于 EOF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3714090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:50:00  来源:igfitidea点击:

How to see if a Reader is at EOF?

javaeof

提问by Melody Horn

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 sis null, which is no good. Is there any Readerthat has an atEOF()method or equivalent?

但是,如果文件当前为空,s则为 null,这不好。有没有Reader一个具有atEOF()方法或等同?

采纳答案by Synesso

A standard pattern for what you are trying to do is:

您尝试执行的操作的标准模式是:

BufferedReader r = new BufferedReader(new FileReader(myFile));
String s = r.readLine();
while (s != null) {
    // do something with s
    s = r.readLine();
}
r.close();

回答by President James K. Polk

the ready() method will not work. You must read from the stream and check the return value to see if you are at EOF.

ready() 方法将不起作用。您必须从流中读取并检查返回值以查看您是否处于 EOF。

回答by 18446744073709551615

The docssay:

文件说:

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.

public int read() throws IOException
返回: 读取的字符,为 0 到 65535 (0x00-0xffff) 范围内的整数,如果已到达流的末尾,则返回 -1。

So in the case of a Reader one should check against EOF like

所以在读者的情况下,应该检查 EOF 就像

// Reader r = ...;
int c;
while (-1 != (c=r.read()) {
    // use c
}

In the case of a BufferedReader and readLine(), it may be

在 BufferedReader 和 readLine() 的情况下,它可能是

String s;
while (null != (s=br.readLine())) {
    // use s
}

because readLine() returns null on EOF.

因为 readLine() 在 EOF 上返回 null。

回答by KIM Taegyoon

Use this function:

使用这个功能:

public static boolean eof(Reader r) throws IOException {
    r.mark(1);
    int i = r.read();
    r.reset();
    return i < 0;
}