Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read all lines with BufferedReader

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?

like image 970
deadpixels Avatar asked Mar 11 '15 01:03

deadpixels


People also ask

How do you read multiple lines in a buffer reader?

Another way to read multiple lines from the console can be done using the synchronized BufferedReader class in Java. The idea is to read each line using the readLine() method and use String. split() to split the line into individual tokens using whitespace as a delimiter. We can also use the StringTokenizer class.

What is readLine () in Java?

The readLine() method of Console class in Java is used to read a single line of text from the console. Syntax: public String readLine() Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console.

Does BufferedReader readLine include newline?

BufferedReader The readLine() method reads a line of text from the file and returns a string containing the contents of the line, excluding any line-termination characters or null.


1 Answers

One line of code using Java 8:

line =  buffer.lines().collect(Collectors.joining()); 
like image 136
Russel Yang Avatar answered Oct 03 '22 14:10

Russel Yang