How to see if a Reader is at EOF?

为君一笑 提交于 2019-12-01 14:59:11

问题


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?


回答1:


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();



回答2:


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

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

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

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

because readLine() returns null on EOF.




回答3:


Use this function:

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



回答4:


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



来源:https://stackoverflow.com/questions/3714090/how-to-see-if-a-reader-is-at-eof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!