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?
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.
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?
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