如何查看读者是否在EOF?

Mel*_*orn 9 java eof

我的代码需要读入所有文件.目前我正在使用以下代码:

BufferedReader r = new BufferedReader(new FileReader(myFile));
while (r.ready()) {
  String s = r.readLine();
  // do something with s
}
r.close();
Run Code Online (Sandbox Code Playgroud)

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

184*_*615 5

文件说:

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

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

// Reader r = ...;
int c;
while (-1 != (c=r.read()) {
    // use c
}
Run Code Online (Sandbox Code Playgroud)

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

String s;
while (null != (s=br.readLine())) {
    // use s
}
Run Code Online (Sandbox Code Playgroud)

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


Syn*_*sso 1

您想要做的事情的标准模式是:

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

  • read() 方法仅告知下一次读取是否会阻塞。如果 Reader 处于 eof,则下一个调用将不会阻塞;它将立即返回并带有 EOF 指示(readline 为 null,read 为 -1)。 (4认同)