8

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?

skaffman
  • 381,978
  • 94
  • 789
  • 754
gingergeek
  • 219
  • 3
  • 7
  • 12

2 Answers2

16

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());
}

John Kugelman
  • 307,513
  • 65
  • 473
  • 519
  • It's a pity there is still no better solution than creating one Scanner per line, though. I stumbled upon the same problem as your first "naive" solution, the Scanner reads too much ahead and there doesn't seem to be any way to set a smaller buffer. – Joffrey Mar 21 '17 at 01:35
10

Just put a counter in the 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());
}
Ry4an Brase
  • 77,054
  • 6
  • 143
  • 167
  • 2
    I think this only works if you have .useDelimiter() set to newline. If you scan for whitespace (e.g. words) than it will count words instead. – Roalt Sep 22 '10 at 12:32
  • 1
    I updated the example to use hasNextLine/nextLine so that it solves the OP's question. – black panda Dec 30 '11 at 04:13