How should I read from a buffered reader?

前端 未结 9 969
無奈伤痛
無奈伤痛 2020-12-06 08:26

I have the following example of reading from a buffered reader:

while ((inputLine = input.readLine()) != null) {
   System.out.println(\"I got a message from         


        
9条回答
  •  不思量自难忘°
    2020-12-06 09:08

    When the socket on the other end is closed, the reader should return a null string. This is the condition that you are looking for. To handle the exception, wrap the reading loop in a try/catch block.

     try {
       while ((inputLine = input.readLine()) != null) {
         System.out.println("I got a message from a client: " + inputLine);
       }
     }
     catch (IOException e) {
       System.err.println("Error: " + e);
     }
    

    You might find this tutorial on reading/writing from/to a socket in Java, helpful.

提交回复
热议问题