Don't use println
; use print
instead and add \r
at the end of the line. For example,
System.out.print("Doing x task... " + percentDone + "%\r");
System.out.flush();
The \r
(carriage return) character returns the "insertion point" back to the start of the current line, without advancing to the next one. When you print text after that, it will overwrite the existing line.
When using print
it becomes essential to flush
the output stream manually. Otherwise you won't receive any output until the internal buffer is filled.
Note that this trick does not work in Eclipse, NetBeans and most other IDEs' Console output because they do not interpret the special control characters like \r
or \b
. You must use it from the command line.