Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get line number using scanner

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?

like image 739
gingergeek Avatar asked Aug 26 '09 04:08

gingergeek


2 Answers

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

like image 174
John Kugelman Avatar answered Oct 17 '22 21:10

John Kugelman


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());
}
like image 23
Ry4an Brase Avatar answered Oct 17 '22 21:10

Ry4an Brase