Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stoppable Java console progressbar

I am looking for a way to stop the progress of the following bar:

private static void cancellaaaaaaaaable() throws InterruptedException {
    System.out.println("Cancellaaaaaaable!");
    System.out.print(ANSI_RED);
    for(int i = 0; i < 79; i++){
        // Something that allows user input/interaction capable to stop the progressbar
        System.out.print("█");
        TimeUnit.MILLISECONDS.sleep(500);
    }
    System.out.print(ANSI_RESET);
}

When the progressbar starts, the user should have about 40 seconds to decide to stop and cancel the progress bar.

enter image description here

Is there a way to do that? It's great any keyboard input, except those that brutally stop the process.

like image 878
shogitai Avatar asked Jul 05 '26 09:07

shogitai


1 Answers

Here is a solution inspired from how to read from standard input non-blocking?

The idea is to check whether there is something to read from System.in .

Note that this only works if the input is validated (like with the Enter key), but even an empty input works (Enter key pressed directly), so you could add some "Press Enter to cancel" message .

private static void cancellaaaaaaaaable() throws InterruptedException {
    System.out.println("Cancellaaaaaaable!");
    System.out.print(ANSI_RED);

    InputStreamReader inStream = new InputStreamReader(System.in);
    BufferedReader bufferedReader = new BufferedReader(inStream);
    for (int i = 0; i < 79; i++) {

        System.out.print("█");
        TimeUnit.MILLISECONDS.sleep(500);

        // Something that allows user input/interaction capable to stop the progressbar
        try {
            if (bufferedReader.ready()) {
                break;
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
    System.out.print(ANSI_RESET);
}

Note that you may perform more advanced console things with Java Curses Library for instance.

like image 97
Arnaud Avatar answered Jul 06 '26 23:07

Arnaud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!