aspose file tools*
The moose likes Beginning Java and the fly likes FileReader loop problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "FileReader loop problem" Watch "FileReader loop problem" New topic
Author

FileReader loop problem

omar salem
Ranch Hand

Joined: Aug 22, 2006
Posts: 34
Hi ranchers....would you please look at this code and tell me what's wrong with it?

I am reading data from a file using FileReader class and after reading is done, i am trying to display the content of the file on my screen using this code

int i = fr.read();// where fr is the object of the FileReader class
while(i != -1)
{
System.out.println((char)i);
}


when i perform this, i get only the first character in the file printed on my screen continuously. Is my loop wrong?....i would apprciate correcting me......many thanks in advance


Have a sip of Java !!!
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by omar salem:
...i get only the first character in the file printed on my screen continuously. Is my loop wrong? ...

Yes. Your loop only contains a single println statement. So all it does is print the same char over and over, without ever getting another char from the reader. You need to add a read statement inside the loop.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
There's a neat bit of Java syntax that is not real obvious. Any assignment statement is also an expression with the value of whatever got assigned. So the assignment statement i=fr.read() has the value of whatever i gets. And you can test it in the same line:

That's sure to cause some head scratching the first time you see it (sure did for me) but it's common enough in real code that it will pay to remember it and get used to it.



A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
Don't get me started about those stupid light bulbs.
 
subject: FileReader loop problem