BufferedReader 意外 java.util.NoSuchElementException

Unexpected java.util.NoSuchElementException with BufferedReader

我正在使用 BufferedReader lines() 方法获取文本文件中的特定行。这是代码:

String line = reader.lines().filter(stuff -> stuff.startsWith(string)).findFirst().get(); // This is called inside of another method.

它在我调用该方法的前几次有效,然后它只给我一个 NoSuchElementException。我查看了该文件,确实有一行以所需的 string 变量开头。

如果需要,我会提供更多信息。

It works the first time

所以你已经阅读了所有的台词。所以没有更多的线。所以你看不懂。

A BufferedReader 不可重用,因为它只能向下遍历文件,不能向上遍历。当您最后一次调用 .lines() 时,您已经读取了整个文件,并且 reader 将位于文件的末尾。您可能不希望它到达文件末尾,但根据 docs:

After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line.

要再次可靠地调用 .lines(),您需要再次实例化 BufferedReader。如果要查找文件中的下一个匹配项,请在后续调用中使用 .skip(X).findFirst()