How to get line number using a scanner

I use a scanner to read a text file line by line, but then how to get the line number, since the scanner iterates through each input? My program looks something like this:

s = new Scanner(new BufferedReader(new FileReader("input.txt"))); while (s.hasNext()) { System.out.print(s.next()); 

This works fine, but for example:

 1,2,3 
 3,4,5

I want to know the line number, which means that 1,2,3 is on line 1, and 3,4,5 is on line 2. How do I get this?

+7
java java.util.scanner
source share
2 answers

You can use LineNumberReader instead of BufferedReader to keep track of the line number while the scanner does its job.

 LineNumberReader r = new LineNumberReader(new FileReader("input.txt")); String l; while ((l = r.readLine()) != null) { Scanner s = new Scanner(l); while (s.hasNext()) { System.out.println("Line " + r.getLineNumber() + ": " + s.next()); } } 

Note. The β€œexplicit” solution that I first posted does not work, because the scanner reads before the current token.

 r = new LineNumberReader(new FileReader("input.txt")); s = new Scanner(r); while (s.hasNext()) { System.out.println("Line " + r.getLineNumber() + ": " + s.next()); } 

Strike>

+16
source share

Just put the counter in a loop:

 s = new Scanner(new BufferedReader(new FileReader("input.txt"))); for (int lineNum=1; s.hasNext(); lineNum++) { System.out.print("Line number " + lineNum + ": " + s.next()); } 
+9
source share

All Articles