Read all lines with BufferedReader

后端 未结 7 694
醉梦人生
醉梦人生 2020-12-08 14:24

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

相关标签:
7条回答
  • 2020-12-08 14:49

    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.

    0 讨论(0)
  • 2020-12-08 14:52

    Snarky answer: what you're doing wrong is only creating 2 objects in Java to do something... if you search, you can probably find a few more classes that extend BufferedReader or ExtendedBufferReader etc., and then it can be real Enterprise Java.

    Now that i've gotten that out of my system: more useful answer. System.in is closed when you input EOF, which is Control-D under Linux and I think MacOS, and I think Control-Z plus enter under Windows. If you want to check for enter (or more specifically, two enters... one to finish the last line and one to indicate that you're done, which is essentially how http handles determining when the http headers are finished and it's time for the http body, then @dbank 's solution should be a viable option with a minor fix I'm going to try to make to move the ! inside the while predicate instead of !while.

    (Edit #2: realized readLine strips the newline, so an empty line would "" instead of the newline, so now my code devolves to another answer with the EOF bit as an answer instead of comment)

    Edit... that's weird, @dbank had answered while I was typing my answer, and I would have stopped had I not though mentioning the EOF alternative. To repeat his code from memory with the edit I was going to make:

    InputStreamReader instream = new InputStreamReader(System.in);
    BufferedReader buffer = new BufferedReader(instream);
    
        line= buffer.readLine();
        while (line != null && !line.equals("")){
            length = length + line.length();
            line= buffer.readLine();
        }
    
    0 讨论(0)
  • 2020-12-08 14:57

    One line of code using Java 8:

    line =  buffer.lines().collect(Collectors.joining());
    
    0 讨论(0)
  • 2020-12-08 15:00

    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();
        }
    
    0 讨论(0)
  • 2020-12-08 15:04

    Put every lines into String[] array. and second method get the number of lines contains in text file. I hope this might be useful to anyone..

    public static void main(String... args) throws IOException {
        String[] data = getLines();
        for(String v : data) {
            out.println(v);
        }
    }
    
    public static String[] getLines() throws IOException {
        BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
        String line = bufferReader.readLine(); 
        String[] data = new String[getLinesLength()];
        int i = 0;
        while(line != null) {
            data[i] = line; 
            line = bufferReader.readLine();
            i++;
        }
        bufferReader.close();
        return data;
    }
    
    public static int getLinesLength() throws IOException {
        BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
        String line = bufferReader.readLine(); 
        int size = 0;
        while(line != null) {
            size += 1;
            line = bufferReader.readLine();
        }
        bufferReader.close();
        return size;
    }
    
    0 讨论(0)
  • 2020-12-08 15:09

    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! :)

    0 讨论(0)
提交回复
热议问题