The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
October 2000



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Unthrustworthy BufferedReader.ready() ?

Posted by Pedro Borges on October 04, 2000 at 1:10 PM

Hello there, I am posting this unusual behavior I got from combining BufferedReader.ready() and BufferedReader.readLine() when trying to patch an example from SUN's JAVA tutorial.
The example in question is "Reading from and Writing to a Socket"

-------------------- ORIGINAL EXAMPLE CODE


public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("your.mail.server", 25);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(;
String userInput;
while ((userInput = stdIn.readLine()) != null) {
System.out.println("echo: " + in.readLine());


This example works fine except for the fact it expects exactly one line of text as the reply to any single line of command. So I felt compelled to patch the code to alow multiple response lines to a single command, thus having:

2 while ((userInput = stdIn.readLine()) != null) {
3 out.println(userInput);
4 while(in.ready()){
5 System.out.println("echo: " + in.readLine());
6 }
7 }

Now, for my surprise I get in.readLine() to block immediately! Well I think... there can be a case when I have data ready for reading wich isn't \n \r or \r\n terminated (wich isn't even the case), but I pached on (I'll spare you from the code) and found that if I have in BufferedReader a "foo\n" string waiting, I have .ready() == true; Ok, if I .read() 4 times I get 'f' 'o' 'o' '\n' respectively and .ready() == false; Ok, but if I .readLine() it, I get "foo\n" but .ready() STILL ON !!!

Also weird is the fact of in.ready() == false in line 1, and true in line 3 !
On my tests I connected to a local sendmail port, wich starts service negotiation with an instant status line - in.ready() on line 1 SHOULD be true (!)

Any info on this is highly appreciated,
Thank you in advance for your time,

Pedro Borges @ Portugal

  • Maybe a bug Andrea Luciano July 17, 2001 at 5:37 AM (0)

Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us