Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top