Java – How to make the display of a line in the command-line java program change without displaying a new line

command linejava

I'm making a java command line program.

How can I change the contents of a line I've already displayed?

So, for example I could display:

Status: 0%
Status: 2%

Status: 50%

Except, rather than continuing to push down each new line, I simply change the contents of the existing line, so the % done changes in place.

I've seen some console programs do this before, so how can I do it in java?

Best Answer

In most cases, you can output a carriage return (\r) rather than a newline (\n). This depends on the terminal supporting it, which most do. \r moves the cursor back to the beginning of the line.

EDIT: Obviously, when doing this, use System.out.print rather than System.out.println (or just generally use the plain, not ln, form of the output method you're using) -- since the ln suffix means that your text is automatically followed with a newline.

Example:

for (n = 10000; n < 10010; ++n) {
    System.out.print(String.valueOf(n) + "\r");
}
System.out.println("Done");

When this finishes, you'll probably have this on your console screen:

Done0

...since "Done" is shorter than the longest previous thing you output, and so didn't completely overwrite it (hence the 0 at the end, left over from "10010"). So the lesson is: Keep track of the longest thing you write and overwrite it with spaces.