Make the console wait for a user input to close

I have a console application that after performing its tasks, must give feedback to the user, such as "operation completed" or "operation failed" and the detailed error.

The thing is, if I just "let it run", the output message will be printed but the console will close shortly afterwards, leaving no time to read the message.

As far as I remember, in C++, every console application will end with a "press any key to exit" or something like that. In C# I can simulate this behavior with a

Console.ReadKey();

But how can I do it in Java? I'm using the Scanner class, but given that "input" is my instance of Scanner:

input.next()
System.exit(0);

"Any key" will work, except for return, which is quite a big deal here. Any pointers?


In Java this would be System.in.read()


I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a pipeline) there is no point printing a message or waiting. For that you could use Java's Console like this:

import java.io.Console;
// ...
public static void waitForEnter(String message, Object... args) {
    Console c = System.console();
    if (c != null) {
        // printf-like arguments
        if (message != null)
            c.format(message, args);
        c.format("\nPress ENTER to proceed.\n");
        c.readLine();
    }
}

The problem with Java console input is that it's buffered input, and requires an enter key to continue.

There are these two discussions: Detecting and acting on keyboard direction keys in Java and Java keyboard input parsing in a console app

The latter of which used JLine to get his problem solved.

I personally haven't used it.


You can just use nextLine(); as pause

import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);

void Read()
{
     System.out.print("Press any key to continue . . . ");
     scan.nextLine();
}

However any button you press except Enter means you will have to press Enter after that but I found it better than scan.next();