如何查看读者是否在EOF?

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

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

但是,如果文件当前为空,则s为null,这是不好的。 是否有任何具有atEOF()方法或等效的Reader

您要尝试的标准模式是:

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

文档说:

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

所以在阅读器的情况下,应该检查EOF

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

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

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

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

使用此function:

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

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