Java 从标准输入接受一 (1) 个多行字符串

Java accepts one (1) multiline string from stdin

我正在编写一个程序,它既可以接受“.sql”文件,也可以接受来自标准输入的 SQL 语句。问题来自标准输入:

Scanner scanner = new Scanner(new BufferedInputStream( System.in));
System.out.println("Enter SQL statements");
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext()) {
    stringBuilder = stringBuilder.append(scanner.nextLine()).append("\n");
}
sqlQuery=stringBuilder.toString();

它是根据答案 here. But when I enter or paste the statement(s) into the terminal, it does not go to the next step, instead the statement keeps appending "\n". I want the user input to end after they hit enter (similar to this problem 但在 Java 中修改的。我该怎么做?

您提供的代码预期输入将在 Scanner 关联的流的末尾终止,而不是在一行的末尾终止——看看 scanner.nextLine() 调用在 while 循环内?

如果你只想读一行,那就去掉循环。此外,如果您不连接多行,那么您也不需要 StringBuilder 。但是,请确保这是您想要的,因为 SQL 语句以多行格式编写是相对常见的。

要收集双换行(空白行)之前的所有输入,您可以使用正则表达式在 Scanner 上设置自定义分隔符,它将通过一次调用收集输入至 scanner.next().

Scanner scanner = new Scanner(System.in);

System.out.println("Enter SQL statements");

scanner.useDelimiter("\n\n"); // an empty line
String sqlQuery = scanner.next();
scanner.reset(); // resets the delimiter