When the program has not yet read from the stream, the ready () method returns false, although in fact there is something to read in the stream. And if you read it once, then ready () works correctly. Why is this so? Here is a sample program:

import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.net.Socket; import java.io.IOException; import java.util.*; public class Server { public static void main(String[] args) { try { String ip = ""; //любой работающий веб сервер int port = 25; //любой Socket socket = new Socket(ip, port); InputStreamReader reader = new InputStreamReader(socket.getInputStream()); String str = ""; System.out.println(reader.ready()); str += (char) reader.read(); System.out.println(reader.ready()); while(reader.ready()) { str += (char) reader.read(); } System.out.println("End read - " + str); reader.close(); socket.close(); } catch(IOException exp) { System.out.println("Error"); } } } 
  • Why do you think it should work differently? - Roman C

1 answer 1

From the documentation:

Tells whether it is ready to be read. The inputStreamReader is ready if it’s not.

Overrides:

ready in class reader

Returns:

For false, otherwise otherwise. Note that the return read will block.

Throws:

IOException - If an I / O error occurs

According to this, the data before reading is most likely blocked and available after the start of reading. I had the same situation when reading serialized objects from a file.

It is generally not recommended to check for the availability of data through ready (), since this method is not for this. It is better to check that read () returns a value, if it returns -1, then there is no more data.

For example, as when using the BufferedReader, it checks whether the readline () method returned a new string.

 String line = in.readLine(); while(line != null){ ... line = in.readLine(); }