【问题标题】:How to see if a Reader is at EOF?如何查看 Reader 是否在 EOF?
【发布时间】:2010-09-15 01:35:44
【问题描述】:

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

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

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

【问题讨论】:

    标签: java eof


    【解决方案1】:

    docs 说:

    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。

    【讨论】:

    • 字符或行在读取后不会不可访问吗?除非显式重置位置,否则这看起来像是从流中丢弃字节。 (特别是如果用户想在不消耗更多字节的情况下检查 EOF)
    • @Kcits 这就是为什么在每种情况下都声明一个变量的原因;在比较之前,该变量被写入: while (-1 != ( c=r.read() )
    【解决方案2】:

    使用此功能:

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

    【讨论】:

    • 当且仅当Reader支持mark()reset()
    【解决方案3】:

    您尝试做的标准模式是:

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

    【讨论】:

    • ready() 方法只告诉下一次读取是否会阻塞。如果 Reader 在 eof 下一次调用不会阻塞;它将立即返回并带有 EOF 指示(readline 为 null,read 为 -1)。
    • 更好:do-while 而不是 while。
    • BufferedReader.readLine() 的 JavaDoc 说它返回“一个包含该行内容的字符串...或 null 如果已到达流的结尾”跨度>
    • 如果我的文件包含null 作为字符串会怎样?我无法读取完整文件,这是一个原因吗?
    • @I-droid "null"null 是两个完全不同的东西。
    【解决方案4】:

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

    【讨论】:

    • 嗯,它在许多情况下工作,但它不能满足回答这个问题所需要的。
    猜你喜欢
    • 2014-04-03
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    相关资源
    最近更新 更多