Home > Enterprise >  Use BufferedReader to recognize the end of a txt file
Use BufferedReader to recognize the end of a txt file

Time:09-29

I have made code that uses BufferedReader and read() to access and read text from a txt file one character at a time. The intended result is to print one word at a time from the txt file to the console. My current difficulty is that, once the whole file has been read through, it seems to cycle through the txt file over and over again, when I want to read it only once. How can I prevent the code from repeating the process? is there a value I can make the while loop recognize?

https://i.stack.imgur.com/ABPQT.png

CodePudding user response:

BufferedReader.read() returns an int, whose value is -1 when you reach the end of the file. So:

int read;
// Remove the reader.read() before the loop.
while ((read = reader.read()) >= 0) {
  char held = (char) read;

  // Rest of the loop.

  // Remove the reader.read() at the end of the loop.
}
  • Related