BufferedReader.readLine() waits for input from console

笑着哭i 提交于 2019-12-06 00:59:41

问题


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

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



回答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.



来源:https://stackoverflow.com/questions/14581205/bufferedreader-readline-waits-for-input-from-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!