Read all lines with BufferedReader

deadpixels picture deadpixels · Mar 11, 2015 · Viewed 77.2k times · Source

I want to type a multiple line text into the console using a BufferedReader and when I hit "Enter" to find the sum of the length of the whole text. The problem is that it seems I'm getting into an infinite loop and when I press "Enter" the program does not come to an end. My code is below:

InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);

    line= buffer.readLine();

    while (line!=null){
        length = length + line.length();
        line= buffer.readLine();
    }

Could you please tell me what I'm doing wrong?

Answer

Russel Yang picture Russel Yang · Nov 4, 2016

One line of code using Java 8:

line =  buffer.lines().collect(Collectors.joining());