How to check the end of line using Scanner?

user1806722 picture user1806722 · Mar 3, 2013 · Viewed 41.5k times · Source

I have searched similar questions, but none helped.

Consider a file :

hi how are you?
where were you?

I want to do few operations after the end of every line. If I use next() it wont tell me when I have reached the end of the first line.

Also I have seen hasNextLine() but it only tells me if there exists another line or not.

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Mar 3, 2013

Consider using more than one Scanner, one to get each line, and the other to scan through each line after you've received it. The only caveat I must give is that you must be sure to close the inner Scanner after you're done using it. Actually you will need to close all Scanners after you're done using them, but especially the inner Scanners since they can add up and waste resources.

e.g.,

Scanner fileScanner = new Scanner(myFile);
while (fileScanner.hasNextLine()) {
  String line = fileScanner.nextLine();

  Scanner lineScanner = new Scanner(line);
  while (lineScanner.hasNext()) {
    String token = lineScanner.next();
    // do whatever needs to be done with token
  }
  lineScanner.close();
  // you're at the end of the line here. Do what you have to do.
}
fileScanner.close();