BufferedReader.readLine () is waiting for console input

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

The following is a snippet of code:

    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("~");
}
+5
source share
2 answers

The code below may fix, replace the text exitwith a string with a specific requirement

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

When reading from the console, you need to determine the "final" input, since the console (unlike the file) never ends (it continues to work even after the end of your program).

There are several solutions to your problem:

  • -: java ... < input-file

    , EOF.

  • EOF . Linux Mac Ctrl+D, Windows, Ctrl+Z + Enter

  • , . , Enter.

PS: . readLine(), .

+1

All Articles