theTechnoKid theTechnoKid - 1 year ago 106
Java Question

Unexpected java.util.NoSuchElementException with BufferedReader

I am using the BufferedReader

method to get a specific line in a text file. Here is the code:

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

It works the first couple of times I call the method, then it only gives me a
afterward. I have looked at the file and there indeed is a line that starts with the desired

I will give any more information if needed.

Answer Source

A BufferedReader is not reusable, as in, it can only traverse down the file, not up. When you call .lines() that last time, you have read the entire file, and the reader will be positioned at the end of the file. You may not be expecting it to have reached the end of the file yet, but as per the 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.

To reliably call .lines() again, you need to instantiate the BufferedReader again. If you want to find the next occurrence in the file, use .skip(X).findFirst() on the subsequent calls.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download