5

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?

Community
  • 1
  • 1
AHL
  • 738
  • 3
  • 11
  • 35

2 Answers2

5

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.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • 1
    Andreas - I am printing to the Terminal on my Ubuntu and it works like a charm. Thank you. – AHL Jan 22 '13 at 12:54
  • BTW: The link which @Reza posted suggests to use "\r" to go to the start of the line, which might be even easier - you simply have to reprint the whole line then. – Andreas Fester Jan 22 '13 at 13:03
1

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?

Community
  • 1
  • 1
RGO
  • 4,586
  • 3
  • 26
  • 40
  • I tried the approach you are referring to, and it works, too. Can I mark two questions as correct? If I tick this answer, the above one gets unticked. – AHL Jan 23 '13 at 02:12
  • @AHL As far as I know, only one answer could be "accepted". Please see here: [http://meta.stackexchange.com/questions/40200/can-i-accept-two-answers](http://meta.stackexchange.com/questions/40200/can-i-accept-two-answers) – RGO Jan 23 '13 at 03:55