Read all lines with BufferedReader

95,590

Solution 1

One line of code using Java 8:

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

Solution 2

The idiomatic way to read all of the lines is while ((line = buffer.readLine()) != null). Also, I would suggest a try-with-resources statement. Something like

try (InputStreamReader instream = new InputStreamReader(System.in);
        BufferedReader buffer = new BufferedReader(instream)) {
    long length = 0;
    String line;
    while ((line = buffer.readLine()) != null) {
        length += line.length();
    }
    System.out.println("Read length: " + length);
} catch (Exception e) {
    e.printStackTrace();
}

If you want to end the loop when you receive an empty line, add a test for that in the while loop

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

JLS-14.15. The break Statement says

A break statement transfers control out of an enclosing statement.

Solution 3

line will not be null when you press enter; it will be an empty string.

Take note of what the BufferedReader JavaDoc says about readLine():

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

And readLine() returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

So when you press [Enter], you are giving the BufferedReader a new line containing only \n, \r, or \r\n. This means that readLine() will return an empty string.

So try something like this instead:

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

line = buffer.readLine();

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

Solution 4

When you only press Enter the return from buffer.readLine(); isn't null it is an empty String.

Therefore you should change line != null to !line.equals("") (You could also change it to line.length() > 0)

Now your code will look something like this:

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

line = buffer.readLine();

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

This should solve your problem. Hope this helped! :)

Solution 5

Since Java 8 you can use BufferedReader#lines method directly on buffered reader.

    try (InputStreamReader in = new InputStreamReader(System.in);
         BufferedReader buffer = new BufferedReader(in)) {
        final int length = buffer.lines().mapToInt(String::length).sum();
        System.out.println("Read length: " + length);
    } catch (Exception e) {
        e.printStackTrace();
    }
Share:
95,590
deadpixels
Author by

deadpixels

Updated on May 15, 2021

Comments

  • deadpixels
    deadpixels about 3 years

    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?

  • Stephen Buttolph
    Stephen Buttolph about 9 years
    Because the OP is reading from system.in won't this never end? Wouldn't it just wait for the users next input?
  • Elliott Frisch
    Elliott Frisch about 9 years
    @StephenB It will end on EOF (or ctrl-d); possibly also with ctrl-c and/or ctrl-brk.
  • Stephen Buttolph
    Stephen Buttolph about 9 years
    But I think he wants it to end when he presses Enter.
  • deadpixels
    deadpixels about 9 years
    It does not end with Enter indeed :/
  • deadpixels
    deadpixels about 9 years
    This works indeed, but for some reason I have to press Enter twice. Any idea why that is?
  • Elliott Frisch
    Elliott Frisch about 9 years
    @deadpixels Edited to add break.
  • Stephen Buttolph
    Stephen Buttolph about 9 years
    @deadpixels When I run the program it terminates at the first empty line. Does the counter go up when you press Enter?
  • Stephen Buttolph
    Stephen Buttolph about 9 years
    I may be wrong. But I don't think the returned String actually contains the end line character. If it did then a System.out.println(buffer.readLine()); would have another line at the end right?
  • Radiodef
    Radiodef about 9 years
    Also in the JavaDoc you linked to: "returns [...] the contents of the line, not including any line-termination characters".
  • dbank
    dbank about 9 years
    @StephenB and @RadioDef: Ah my mistake! You are both right. I was confused with read() and who knows what.
  • Radiodef
    Radiodef about 9 years
    while(!line.isEmpty()) {...} like you had before you deleted was correct... (Besides the fact that some have also pointed out that readLine can still return null if the user does something obscure.)
  • dbank
    dbank about 9 years
    I edited to correct my answer. @StephenB and RadioDef, thank you both for calling me out and correcting me so that I didn't spread misinformation.
  • skaffman
    skaffman about 9 years
    Arguably, the idiomatic way is now buffer.lines().
  • Foon
    Foon about 9 years
    To the down voter(s): if this was because of the snarky answer at the top, byte me (I mean, new Byte []("me".getBytes(Charset.forName("UTF-8"))). Otherwise, I'm curious why the downvotes: My code is similar to others (and when I posted @dbank's answer appeared, disappered, and now reappearered; you can't see it now at the 9 hour mark, but my answer was posted marginally before the others) and I also mention the EOF option (which is also useful when piping)
  • Brett Y
    Brett Y over 4 years
    Do I need to include a newline as a delimiter to preserve lines?
  • Wumba
    Wumba about 3 years
    Yes, you have to add a possible separator to preserve lines: buffer.lines() .collect(Collectors.joining(System.lineSeparator()));