如何查看 Reader 是否处于 EOF?

发布于 2024-09-19 12:34:09 字数 313 浏览 3 评论 0原文

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

雪花飘飘的天空 2024-09-26 12:34:09

文档 说:

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

因此,在 Reader 的情况下,应检查 EOF,如

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

In对于 BufferedReader 和 readLine() 的情况,可能是

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

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

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.

弃爱 2024-09-26 12:34:09

使用这个函数:

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

Use this function:

public static boolean eof(Reader r) throws IOException {
    r.mark(1);
    int i = r.read();
    r.reset();
    return i < 0;
}
往日情怀 2024-09-26 12:34:09

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

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

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();
旧瑾黎汐 2024-09-26 12:34:09

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文