Search code examples
javainputstreambufferedreader

read all lines from string buffered reader


I have simple client/server program that sends and recieves strings from client to server and vice versa. Some string contain newline characters "n\", eg "ERR\nASCII: OK"

my buffered reader:

BufferedReader in =
                new BufferedReader(
                    new InputStreamReader(ConverterSocket.getInputStream()));

I am trying to display each line in the string to the user/ client.

I have tried the following for loop:

for (line = in.readLine(); line != null; line = in.readLine()){
                    System.out.println(line);
                }

output (as expected):

ERR
ASCII: OK

but the loop doesn't end. I have also tried:

   while ((line = in.readLine()) != null){
        system.out.println(line)
    }

which also doesn't end properly. How can i print all lines in the string?


Solution

  • The readLine() method returns null at end of stream, which doesn't occur until the peer closes the connection.