Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

BufferedReader problem

 
Dominic Steng�rd
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey JavaGurus!

Ive got the following code:



The code runs well until the last line from the BufferedReader object (din) is printed out in the while loop. The flow seems to freeze after that line has been printed. It doesnt leave the loop, yet the while-loop doesnt seem to keep on looping.

Any thoughts?
Thanks in advance
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you reading from a file or from a Socket? If it's a Socket, it might be that readLine() doesn't return null after the data is read from the Socket.
 
Jeff Storey
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may want to also try
while ( din.ready() ) {
System.out.println(din.readLine());
}
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15438
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You seem indeed to be reading from a socket. A socket doesn't have an "end of file", i.e. there is never a "last line" to be read, so readLine() will never return null. When there's no data coming in on the socket connection, readLine() will just block and wait until data comes in.

Calling ready(), like Jeff suggests, is not a reliable way to check if you've read everything. The computer on the other side of the socket may send data at any speed it likes - it may pause for a short while in between sending data, and for that short while your call to ready() will return false, and you'll think you're done reading the data, while that isn't really so.

The only way you can get this right is that you have to build something into the application-level protocol that you're talking over the socket. In that protocol, there must be some sign that tells you that you have all the data. In other words, the other side has to send you a command or special string that indicates that you're at the end of the data, and in your receiving end you look for that to see if you're done.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm, I read from URL until null. Isn't that just a dressed up socket? I think you'll get null if the other end closes the socket. Here's a bit from the socket tutorial. It uses both null and a terminator in the protocol.

[ November 22, 2006: Message edited by: Stan James ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic