Re: Scanner class and last line in a file
- From: Lew <conrad@xxxxxxxxxxx>
- Date: Sun, 24 Sep 2006 17:25:34 -0400
DemonWasp wrote:
....
First, I tried using the following:
File InFile=new File("input.txt");
Scanner In=new Scanner(InFile);
String Ln;
for ( Ln=In.nextLine() ; In.hasNextLine() ; Ln=In.nextLine() ) {
// Do stuff with Ln in here.
}
Unfortunately, this moves the "cursor" in the file down one line, and
returns the text skipped - probably not what I was trying to do. Also,
when it gets to the end of the file, hasNextLine() returns false (as
it should) and the loop finishes. Unfortunately, it's still left
precious information in the file!
When I tell it to load the final line using nextLine(), it tries
advancing past the end of the file and gives me a
NoSuchElementException.
...
From the API docs <http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html>:
Scanner.hasNextLine()
"Returns true if there is another line in the input of this scanner. ... The scanner does not advance past any input."
Scanner.nextLine()
"Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line."
In other words, nextLine() is supposed to return the text that was skipped.
If your input has only one line (or zero), the loop will not execute. The initialization will read the one line, then the condition will fail because there is no second line.
When the loop finished and you tried to call nextLine() again (assuming you used the same Scanner instance), it threw the exception because hasNextLine() had already failed. Calling nextLine() when ! hasNextLine() raises the exception.
Try something like:
Scanner in = new Scanner( inFile );
while ( in.hasNextLine() )
{
String line = in.nextLine();
// do something with line
}
(The convention is to name variables with a lower-case first letter.)
- Lew
.
- Follow-Ups:
- Re: Scanner class and last line in a file
- From: DemonWasp
- Re: Scanner class and last line in a file
- References:
- Scanner class and last line in a file
- From: DemonWasp
- Scanner class and last line in a file
- Prev by Date: Error?
- Next by Date: Re: Scanner class and last line in a file
- Previous by thread: Scanner class and last line in a file
- Next by thread: Re: Scanner class and last line in a file
- Index(es):
Relevant Pages
|
|