How should I read from a buffered reader?

前端 未结 9 963
無奈伤痛
無奈伤痛 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:03

    The reader's readLine() will return a string value when it has something read, an empty string when there isn't anything yet, and null when the connection is closed.

    I would recommend wrapping a try/catch around your block of code with the IO function and handle errors appropriately.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-06 09:15
    while ((inputLine = input.readLine()) != null) {
    

    Look at each part of the expression:

    input.readLine()
    

    Returns a String which will be null if the end of the stream has been reached (or throws an Exception on error).

    inputLine = input.readLine()
    

    Assigns this String to inputLine

    ((inputLine = input.readLine()) != null)
    

    Checks that the String that was assigned is not null (end of stream).

    0 讨论(0)
提交回复
热议问题