How to overwrite the previous line in gradle console - for implementing progress bar

Viewed 73

I have a Java console app that has a basic progress bar, implemented using \r. Something like this:

for (int i = 0; i < 20; i++) {
    System.out.print("\r" + i + ""); // notice this uses print, not println

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

At each loop iteration the cursor moves to the beginning of the current line, essentially overwrites what's already there. This worked well.

However I recently migrated the project to using gradle, and this no longer works. I figured out the reason was because the gradle console doesn't show anything when you just do print, only when you do println.

So then I tried using println with the \033[F character which should move the cursor to the beginning of the previous line:

for (int i = 0; i < 20; i++) {
    System.out.println("\033[F" + i + "");

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

but it also doesn't work, the console output was

0
1
2
...

Is there a way to implement a progress bar in the gradle console (with Java code)?

0 Answers
Related