简体   繁体   English

尝试读取多行 cmd 输入

[英]Trying to read multiple lines of cmd input

I'm trying to write a method that:我正在尝试编写一个方法:

  • Prints out a message (Something like: "Paste your input: ")打印出一条消息(类似于:“粘贴您的输入:”)
  • Waits that the user presses enter.等待用户按下回车。
  • Reads all the lines, that got pasted and adds them up in one String.读取所有已粘贴的行并将它们添加到一个字符串中。

(An empty line can be used to determine the end of the input.) (可以使用空行来确定输入的结束。)

The first syso does the printing part and also the first line gets read correctly, but then it never exits the while loop.第一个 syso 执行打印部分,并且第一行也被正确读取,但它永远不会退出 while 循环。 Why?为什么? There has to be an end?一定有结局吗?

public static String readInput(String msg) {
    System.out.print(msg);
    String res = "";
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
        String line;
        while ((line = buffer.readLine()) != null && !line.isBlank())
            res += "\n" + line;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

Ive already seen the following sites, but they all didn't help:我已经看过以下网站,但它们都没有帮助:

Edit:编辑:

The same bug applies for:同样的错误适用于:

public static String readInput(String msg) {
        System.out.print(msg);
        String res = "";
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
            res = buffer.lines().reduce("", (r, l) -> r + "\n" + l);
            System.out.println(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

Edit 2: I've tried this code in my actual project and in a new test-project, but with different results.编辑2:我已经在我的实际项目和一个新的测试项目中尝试过这段代码,但结果不同。 Here is a video of that test. 是该测试的视频。

Why wouldn't use this statement?为什么不使用这个语句?

 while (!(line = buffer.readLine()).isEmpty())

In this case sending empty line will exit the loop.在这种情况下发送空行将退出循环。

Although, if you insert large text with empty lines (for example, the beginning of a new paragraph, or a space between them) will terminate the program.但是,如果您插入带有空行的大文本(例如,新段落的开头或它们之间的空格)将终止程序。

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

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