Java command line interface: having multiple progress indicators on different lines using '\ r'

Part of the command line interface for the program that I am writing causes several progress indicators. Currently, I can update a single line in the console using the \r escape sequence with something like this:

 System.out.printf("\rProcess is %d%% complete", percentageComplete); 

However, carriage returns only return to the beginning of this line. I need a way to return two rows (or, moreover, any number of rows) and both of them / all updates.

Is there any way to do this?

+6
source share
2 answers

I wrote a small project for command line progress indicators that can be executed either by a single liner or by a โ€œmaster / partโ€ - see https://github.com/tomas-langer/cli/tree/master/cli-progress . It also works on Windows - using ANSI escape sequences with native implementation for MS Windows (Chalk + Jansi)

If you want to do more, check out the Chalk library ( https://github.com/tomas-langer/chalk ), which in turn uses Jansi (mentioned in previous posts).

The ansi escape code for the line and the clear line is in the 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 
+4
source

Unfortunately, there is no equivalent \r that moves the cursor up. However, this can be done using ANSI escape sequences if you can assume that you are using an ANSI compatible terminal.

To print your progress bars using ANSI codes you can 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 although almost all terminals use ANSI codes, the Win32 terminal does not work . I have not tested it, but this library looks good if you need to support the built-in Windows terminal as well. It includes a JNI library that will do equivalent things on a Windows terminal, and will automatically decide whether to use the JNI library or ANSI codes. It also has some methods to simplify the use of ANSI codes.

+2
source

Source: https://habr.com/ru/post/924175/


All Articles