简体   繁体   English

BufferedReader.readLine()等待来自控制台的输入

[英]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. BufferedReader.readLine()方法读取一行但在最后一行之后它等待来自控制台的输入。 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("~");
}

The below code might fix, replace text exit with your requirement specific string 以下代码可能会修复,将text exit替换为您的需求特定字符串

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

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 将输入放在一个文件中并使用IO重定向: java ... < input-file

    The shell will hook up your process with the input file and you will get an EOF. shell将使用输入文件连接您的进程,您将获得EOF。

  2. Type the EOF-character for your console. 键入控制台的EOF字符。 On Linux and Mac, it's Ctrl+D , on Windows, it's Ctrl+Z + Enter 在Linux和Mac上,它是Ctrl + D ,在Windows上,它是Ctrl + Z + Enter

  3. Stop when you read an empty line. 读空行时停止。 That way, the user can simply type Enter . 这样,用户只需输入Enter即可

PS: there is a bug in your code. PS:您的代码中存在错误。 If you call readLine() twice, it will skip every second line. 如果你两次调用readLine() ,它将跳过每隔一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM