Search code examples
javastdin

Java accepts one (1) multiline string from stdin


I am writing a program that can either accepts a ".sql" file or accepts an SQL statement from the stdin. The problem comes form stdin:

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();

It is modified from the answer 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 but in Java). How do I do it?


Solution

  • To collect all the input until a double new-line (a blank line), you can set a custom delimiter on the Scanner, using a regex, and it will collect the input with a single call to 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