Re: Scanner class and last line in a file
- From: DemonWasp <jda980@xxxxxxx>
- Date: Mon, 25 Sep 2006 14:06:05 -0400
On Mon, 25 Sep 2006 10:03:55 -0700, dagon@xxxxxxxxx (Mark Rafn) wrote:
DemonWasp <jda980@xxxxxxx> wrote:
What I *was* asking was "how do I get the last line from a file, even
when there is no trailing whitespace?"
I can't repro the problem - help me understand what I'm missing. I'm using
the following test class:
import java.io.*;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) throws Exception {
if (args == null || args.length != 1) {
System.out.println("Specify filename.");
System.exit(1);
}
File input = new File(args[0]);
InputStream is = new FileInputStream(input);
int lineNum=0;
for (Scanner s = new Scanner(is); s.hasNextLine();) {
String line = s.nextLine();
System.out.println(lineNum++ + " " + line);
}
}
}
And input file with no trailing newline created by:
$ cat > testfile
lineone
linetwo^d^d
The following happens:
$ java -cp . ScannerTest
0 lineone
1 linetwo
This is what I'd expect. What's it do for you?
You're not missing anything, your code is subtly different. I figured
out the problem.
In my code, I had:
for ( String ln=in.nextLine() ; in.hasNextLine() ; ln=in.nextLine() )
which works fantastically until it gets to the last line in the file.
The "increment" part of the for loop (ie. ln=in.nextLine()) goes and
gets the last line. Then the second part of the for loop checks
(in.hasNextLine()) and returns false - then it skips the body of the
loop.
This caused the following problems:
1) I missed the last line of input because the loop exited too early.
2) When I tried adding an ln=in.nextLine() statement after the for
loop, to gather the "missing" last line, I triggered a
NoSuchElementException because, clearly, I had already loaded the last
line in the file.
The solution is to make sure that the test is done BEFORE I read in
the next line. So the following code works perfectly:
while(in.hasNextLine()){
ln=in.nextLine()
}
Thanks to everyone for the help.
/DemonWasp
.
- References:
- Scanner class and last line in a file
- From: DemonWasp
- Re: Scanner class and last line in a file
- From: Lew
- Re: Scanner class and last line in a file
- From: DemonWasp
- Re: Scanner class and last line in a file
- From: Mark Rafn
- Scanner class and last line in a file
- Prev by Date: Re: Scanner class and last line in a file
- Next by Date: Re: Scanner class and last line in a file
- Previous by thread: Re: Scanner class and last line in a file
- Next by thread: Re: Scanner class and last line in a file
- Index(es):
Relevant Pages
|
|