Part of the command line interface for a program I'm writing calls for multiple progress bars. I can currently update a single line in the console by using the \r
escape sequence with something similar to this:
System.out.printf("\rProcess is %d%% complete", percentageComplete);
However the carriage return only goes back to the start of that line. I want a way of going back two lines (or more generally, any number of lines) and have them both/all update.
Is there any way of doing this?
I have written a small project for command line progress bars that can do either one liners or a "master/detail" - see https://github.com/tomas-langer/cli/tree/master/cli-progress. It works also on Windows - using ANSI escape sequences with native implementation for MS Windows (Chalk + Jansi)
If you want to do more, check the Chalk library (https://github.com/tomas-langer/chalk) that in turn uses Jansi (mentioned already in previous posts).
The ansi escape code for line up and clear line are in Chalk library. To use them:
import com.github.tomaslanger.chalk.Ansi;
...
System.out.print(Ansi.cursorUp(2)); //move cursor up two lines
System.out.print(Ansi.eraseLine()); //erase current line
Unfortunately there's no equivalent to \r
that moves the cursor up. However, this can be done with ANSI escape sequences, so long as you can assume you're on an ANSI-compliant terminal.
To print your progress bars using ANSI codes, you could do
System.out.printf(((char) 0x1b) + "[1A\r" + "Item 1: %d ", progress1);
System.out.printf(((char) 0x1b) + "[1B\r" + "Item 2: %d ", progress2);
The only problem with ANSI codes is that, while almost all terminals use ANSI codes, the Win32 Terminal doesn't. I haven't tested it, but this library looks like it would be a good thing to look into if you need to support the built in Windows terminal as well. It includes a JNI library that will do equivalent things on the Windows terminal, and will automagically decide whether to use the JNI library or ANSI codes. It also has some methods to make ANSI codes slightly easier to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With