BufferedReader.readLine() waits for input from con

2019-04-09 04:40发布

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

2条回答
倾城 Initia
2楼-- · 2019-04-09 05:08

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.

查看更多
再贱就再见
3楼-- · 2019-04-09 05:11

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("~");
}
查看更多
登录 后发表回答