Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FileReader loop problem

 
omar salem
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic