Re: Scanner class and last line in a file
- From: "Oliver Wong" <owong@xxxxxxxxxxxxxx>
- Date: Mon, 25 Sep 2006 13:51:20 GMT
"DemonWasp" <jda980@xxxxxxx> wrote in message news:r5pdh2dvsta11t72r80ffabmrln33ffrmp@xxxxxxxxxx
I've been having some trouble getting the Scanner class to operate the
way I'd like. I'm doing some fairly basic file IO and I can't seem to
get the class to load the last line/token any way I try.
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.
In your "Do stuff with Ln in here" section, doesn't it process the last line right before exiting the loop?
So, I tried changing it up to be the following:
File InFile=new File("input.txt");
Scanner In=new Scanner(InFile).useDelimiter("\n");
Don't bother with "useDelimiter". I think that'll be a dead end for you.
- Oliver
.
- References:
- Scanner class and last line in a file
- From: DemonWasp
- Scanner class and last line in a file
- Prev by Date: Re: Scanner class and last line in a file
- Next by Date: Re: Error?
- 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
|
|