wood burning stoves 2.0
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "FileReader loop problem" Watch "FileReader loop problem" New topic

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)

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

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
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
I agree. Here's the link: http://aspose.com/file-tools
subject: FileReader loop problem
It's not a secret anymore!