How to get line number using scanner

gingergeek picture gingergeek · Aug 26, 2009 · Viewed 19.9k times · Source

I'm using scanner to read a text file line by line but then how to get line number since scanner iterates through each input?My program is 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 line number of it which mean 1,2,3 is in line 1 and 3,4,5 is in line 2.How do I get that?

Answer

John Kugelman picture John Kugelman · Aug 26, 2009

You could use a LineNumberReader in place of the BufferedReader to keep track of the line number while the scanner does its thing.

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 "obvious" solution I first posted does not work as the scanner reads ahead of 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());
}