BufferedReader.readLine() waits for input from console

34,117

Solution 1

The below code might fix, replace text exit with your requirement specific string

  public static String[] getLinesFromConsole() {
    String strLine = "";
    try {
        // Get the object of DataInputStream
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while ((line = br.readLine()) != null && !line.equals("exit") )
            strLine += br.readLine() + "~";

        isr.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return strLine.split("~");
}

Solution 2

When reading from the console, you need to define a "terminating" input since the console (unlike a file) doesn't ever "end" (it continues to run even after your program terminates).

There are several solutions to your problem:

  1. Put the input in a file and use IO redirection: java ... < input-file

    The shell will hook up your process with the input file and you will get an EOF.

  2. Type the EOF-character for your console. On Linux and Mac, it's Ctrl+D, on Windows, it's Ctrl+Z + Enter

  3. Stop when you read an empty line. That way, the user can simply type Enter.

PS: there is a bug in your code. If you call readLine() twice, it will skip every second line.

Share:
34,117
ambar
Author by

ambar

Updated on July 17, 2020

Comments

  • ambar
    ambar almost 4 years

    I am trying to read lines of text from the console. The number of lines is not known in advance. The BufferedReader.readLine() method reads a line but after the last line it waits for input from the console. What should be done in order to avoid this?

    Please see the code snippet below:

        public static String[] getLinesFromConsole() {
        String strLine = "";
        try {
            // Get the object of DataInputStream
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null)
                strLine += line + "~"; //edited
    
            isr.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return strLine.split("~");
    }
    
  • ambar
    ambar over 11 years
    Is it possible to to end the readLine execution without having an exit string?
  • TheWhiteRabbit
    TheWhiteRabbit over 11 years
    to rerminate the text input process , you need some 'text' to indicate quit or exit.