BufferedReader.readLine() waits for input from console

ambar picture ambar · Jan 29, 2013 · Viewed 32.5k times · Source

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("~");
}

Answer

TheWhiteRabbit picture TheWhiteRabbit · Jan 29, 2013

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("~");
}