How to check the end of a line using a scanner?

I looked for similar questions, but no one helped.

Consider the file:

Hi how are you?
where have you been?

I want to do some operations after the end of each line. If I use next() , it will not tell me when I get to the end of the first line.

I also saw hasNextLine() , but it only tells me if another line exists or not.

+7
source share
2 answers

Consider using multiple Scanners, one to receive each line, and another to scan each line after you receive it. The only caveat I have to give is that you must close the internal scanner after you finish using it. In fact, you will need to close all scanners after you use them, but especially internal scanners, as they can build and consume resources.

eg.

 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(); 
+14
source

You can scan text line by line and split each line in tokens using the String.split() method. So you know when one line ended, as well as all the markers in each line:

 Scanner sc = new Scanner(input); while (sc.hasNextLine()){ String line = sc.nextLine(); if (line.isEmpty()) continue; // do whatever processing at the end of each line String[] tokens = line.split("\\s"); for (String token : tokens) { if (token.isEmpty()) continue; // do whatever processing for each token } } 
+1
source

All Articles