How to see if a Reader is at EOF?

你说的曾经没有我的故事 提交于 2019-12-01 15:52:23

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

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.

Use this function:

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

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

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