Read all lines with BufferedReader

2019-02-06 04:02发布

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?

7条回答
时光不老,我们不散
2楼-- · 2019-02-06 04:53

One line of code using Java 8:

line =  buffer.lines().collect(Collectors.joining());
查看更多
登录 后发表回答