Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java display changing progress on command line

I have written a Java program that loads data from a file and I am displaying the progress of the load on the command line, by printing a message to the screen after every n records, which looks like this:

$> processed 100 records.

$> processed 200 records.

$> processed 300 records.

$> processed 400 records.

$> processed 500 records.

...

However, I would like to just print ONE line, and only update the number, i.e., so that the output always just looks like this:

$> processed < n > records.

How to do this in Java and, is it even possible?

like image 436
AHL Avatar asked Jan 22 '13 12:01

AHL


2 Answers

It depends on your console, but the simplest way is to use the backspace character to move the cursor backwards, in front of the recently printed characters:

int[] step = {100,200,300,400,500};
System.out.print("$> processed < ");
for (int i : step) {
   System.out.print(i + " > records.\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
   Thread.sleep(500);
}

This works on the windows command line, but for example it does not work on the Eclipse console.

You should add some additional logic to count the numbers of characters printed, and not hard-code all these "\b" characters, but calculate the right number depending on the recent output.

As @Reza suggests, using "\r" is even easier:

int[] step = {100,200,300,400,500};
for (int i : step) {
   System.out.print("$> processed < " + i + " > records.\r");
   Thread.sleep(500);
}

It does still not work on the Eclipse console (but is more readable than the backspace approach), but avoids the handling of all the backspace characters. If printing a shorter line than before, it might be necessary to print some additional spaces to clear trailing characters.

like image 126
Andreas Fester Avatar answered Nov 01 '22 23:11

Andreas Fester


You need to find a way to return to the start of a line and overwrite what has already been output on the console. This question has been addressed here:

How can I return to the start of a line in a console?

like image 26
RGO Avatar answered Nov 02 '22 01:11

RGO