Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

when reading a file, how safe is using ready() method in the loop.  RSS feed

 
Ahmet A. Akin
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, sometimes because of lazyness, while looping through a Reader, instead of doing this:



i do this:

while(reader.ready()){
String s=reader.readLine();
}

However, from java docs, it says:
..Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.
Returns:
Returns true if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block.


so now i am not sure if this is a safe thing to do when reading a file. Anybody can clarify this issue, and when is ready() method is useful?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The available() method is useless for determining when you've gotten to the end of the file. It may return false simply because the Reader doesn't have any more characters available right now. Often this simple means that the hard drive is busy moving to another disc sector to find the rest of the file. Or if you're reading from a network connection, perhaps there's a delay in the network, or a user on the other end of the connection is simply still typing. You need to check the return value of read() , as shown in your first code sample above, to know when the stream is really ended. You may also want to read Available Doesn't Do What You Think It Does.
[ January 12, 2008: Message edited by: Jim Yingst ]
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!