473,554 Members | 2,844 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Scanner class and last line in a file

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
NoSuchElementEx ception.
So, I tried changing it up to be the following:

File InFile=new File("input.txt ");
Scanner In=new Scanner(InFile) .useDelimiter(" \n");

String Ln;
for ( Ln=In.next() ; In.hasNext() ; Ln=In.next() ) {
// Do stuff with Ln in here.
}

This, however, according to the method description, only returns those
tokens which both start AND end with the delimiter - making it
impossible for me to use it to load the last token in the file, simply
because there's no newlines after it.
How can I get that last line (preferably, using the Scanner class)? Is
it possible to specify that the EOF sequence is a delimiter - or would
that even work?

Thanks in advance for any help,
DemonWasp

Sep 24 '06 #1
7 25877
Lew
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
NoSuchElementEx ception.
...
From the API docs
<http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html>:

Scanner.hasNext Line()
"Returns true if there is another line in the input of this scanner. ... The
scanner does not advance past any input."

Scanner.nextLin e()
"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
Sep 24 '06 #2
On Sun, 24 Sep 2006 17:25:34 -0400, Lew <co****@comcast .netwrote:

<snip>
>Scanner.hasNex tLine()
"Returns true if there is another line in the input of this scanner. ... The
scanner does not advance past any input."

Scanner.nextLi ne()
"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.
I recognise this, but I probably didn't make it sufficiently clear in
my post. However, this wasn't the main issue.
>If your input has only one line (or zero), the loop will not execute. The
initializati on 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.)
Yeah, but I'm unconventional :P. Again though, this example misses the
point of the question that I was asking.

What I *was* asking was "how do I get the last line from a file, even
when there is no trailing whitespace?"

Thanks anyway,
DemonWasp
Sep 25 '06 #3
DemonWasp wrote:
On Sun, 24 Sep 2006 17:25:34 -0400, Lew <co****@comcast .netwrote:

<snip>
>Scanner.hasNex tLine()
"Returns true if there is another line in the input of this scanner. ... The
scanner does not advance past any input."

Scanner.nextLi ne()
"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.

I recognise this, but I probably didn't make it sufficiently clear in
my post. However, this wasn't the main issue.
>If your input has only one line (or zero), the loop will not execute. The
initializati on 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.)

Yeah, but I'm unconventional :P. Again though, this example misses the
point of the question that I was asking.

What I *was* asking was "how do I get the last line from a file, even
when there is no trailing whitespace?"

Thanks anyway,
DemonWasp
I don't confuse being unconventional with being dense. He just showed
you what you need to do. Personally, I would point you to read the
Scanner api. Learn how to Google the groups also.

--
Thanks in Advance...
IchBin, Pocono Lake, Pa, USA http://weconsultants.phpnet.us
_______________ _______________ _______________ _______________ ______________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor, Regular Guy (1952-)
Sep 25 '06 #4

"DemonWasp" <jd****@msn.com wrote in message
news:r5******** *************** *********@4ax.c om...
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
NoSuchElementEx ception.
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 "useDelimit er". I think that'll be a dead end for you.

- Oliver

Sep 25 '06 #5
DemonWasp <jd****@msn.com 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.Scann er;
public class ScannerTest {
public static void main(String[] args) throws Exception {
if (args == null || args.length != 1) {
System.out.prin tln("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.prin tln(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?
--
Mark Rafn da***@dagon.net <http://www.dagon.net/>

Sep 25 '06 #6
On Mon, 25 Sep 2006 10:03:55 -0700, da***@dagon.net (Mark Rafn) wrote:
>DemonWasp <jd****@msn.com 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.Scann er;
public class ScannerTest {
public static void main(String[] args) throws Exception {
if (args == null || args.length != 1) {
System.out.prin tln("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.prin tln(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
NoSuchElementEx ception 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.hasNex tLine()){
ln=in.nextLine( )
}

Thanks to everyone for the help.
/DemonWasp

Sep 25 '06 #7
DemonWasp <jd****@msn.com wrote:
>I've been having some trouble getting the Scanner class to operate the
way I'd like.
Came back to read the OP to see what I'd missed. You misstate the problem.
It's not the Scanner doing the wrong thing, you're confused about how a for()
loop works.
>for ( Ln=In.nextLine( ) ; In.hasNextLine( ) ; Ln=In.nextLine( ) ) {
// Do stuff with Ln in here.
}
Remember,
for( a; b; c) { d }
is exactly translatable as
{ a; while (b) { d; c; }

I'm unwilling to put up with stupidly nonstandard naming, so I'll just pretend
your variables are lowercase. Your code is identical to:

ln=in.nextLine( );
while (in.hasNextLine ) {
// do stuff
ln = in.nextLine();
}

This is just wrong. You're getting line 0, then test for line n+1 before
processing line n and getting n+1. You'll blow up with empty input, and skip
processing the last line. You'll GET the last line, as the last part of
processing the previous, but your loop condition is now false, so you won't
process it.
>Unfortunatel y, 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!
Nope, it left the information in your ln variable.
>When I tell it to load the final line using nextLine(), it tries
advancing past the end of the file and gives me a
NoSuchElementE xception.
As it should. You already read the last line, you just haven't processed it
yet.
>How can I get that last line (preferably, using the Scanner class)? Is
it possible to specify that the EOF sequence is a delimiter - or would
that even work?
You _ARE_ getting the last line. you're just discarding it by getting it at
the end of your loop rather than the beginning. try the following:
in = new Scanner(input);
while (in.hasNextLine ) {
ln = in.nextLine();
// do stuff
}
or (if you want your locals to conveniently go out of scope after the loop
for (in = new Scanner(input); in.hasNextLine; ) {
String ln = in.nextLine;
// do stuff
}
--
Mark Rafn da***@dagon.net <http://www.dagon.net/>
Sep 25 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
5869
by: Ridimz | last post by:
When use ifstream, how do I ignore the last line of a file if it doesn't contain any information? Thanks in advance, Ridimz
4
10245
by: Charles Erwin | last post by:
Is there any way, upon scanning in a file line by line to avoid missing the last line if there is not a newline character (aka you have to hit return on the last line of input in your file). I was sure that there was a way around it but it escapes me if there is one. Thanks Charles Erwin
16
796
by: DJP | last post by:
Hi, I need to read a file programmatically until end of file. My logic is as follows: while(!feof(Fp)) { fgets(readLine,10000,Fp);
2
3808
by: Eric Lilja | last post by:
Hello, I'm writing a simple program that upon start-up needs to open a text file and read a value on the last line. Then all other accesses to the file will be writes (at the end of it). I'm having two problems with this...I tried opening the file for both writing and reading with: std::fstream file("budget.txt", std::ios_base::in |...
35
11381
by: RyanS09 | last post by:
Hello- I am trying to write a snippet which will open a text file with an integer on each line. I would like to read the last integer in the file. I am currently using: file = fopen("f.txt", "r+"); fseek(file, -2, SEEK_END); fscanf(file, "%d", &c); this works fine if the integer is only a single character. When I get into larger...
6
5770
by: magix | last post by:
Hi, when I read entries in file i.e text file, how can I determine the first line and the last line ? I know the first line of entry can be filtered using counter, but how about the last line of entry in EOF while loop ? while (! file.eof() ) { ....
3
1891
by: CCLeasing | last post by:
Hi i'm trying to check if the last line in a file is equal to a string i'm comparing it with. I have the general idea of what I should be doing. Could someone take a look at the following and comment it or suggest improvements. As code it doesn't work at the moment but I hope from it you can see what i'm trying to do. private bool...
14
2403
tolkienarda
by: tolkienarda | last post by:
hi all i read the scanner class documentation from sun's website and i thought i would have some fun trying to write a program that stores a line from the user to var input and then parses it on white space then depending on what the new string is i will do somthing. i think there is an easier way than what i am trying but i am just trying to get...
7
5176
by: kidosai | last post by:
hi i need a guide on how to use the scanner class... i need to use Java Scanner class to read a text file and be able to print the text inside of it... example : i have a text file named "myFile.text" inside of it there are text writen or listed on it... Alvin Simon
0
7499
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8013
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7531
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7862
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6120
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5136
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3539
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1994
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1112
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.