Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader.readLine() waits for input from console

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("~");
}
like image 636
ambar Avatar asked Jan 29 '13 10:01

ambar


1 Answers

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("~");
}
like image 173
TheWhiteRabbit Avatar answered Sep 28 '22 16:09

TheWhiteRabbit