views:

99

answers:

2

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?

+3  A: 

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.

T.J. Crowder
Will this not append the output to the previously outputted "print"?
Some code I know uses `\b` to "backspace out" the bits to replace, rather than replacing the whole line with `\r`.
Chris Jester-Young
@Isharyan: `\r` puts the cursor at the start of the line ("for most terminals"), so anything you append after it will appear at the start of the line.
Chris Jester-Young
@lsharyan: Sorry, I should have said what Chris said in the answer. I'll edit it.
T.J. Crowder
@Chris Jester-Young: if the next line to come up is physically less spaces than the previous, how do I ensure I don't have any hanging remnants of the last line? Append a bunch of spaces or?
@lsharyan: Yup, included a note about that in my edit just now in fact.
T.J. Crowder
+2  A: 

Take a look at this example.

Working code:

public class progress {
    public static void main(String[] args) throws InterruptedException { 
     for (int i = 0; i <= 100; i++) {
      Thread.sleep(30);
      System.out.print("\rSTATUS: "+i+" % " );
     } 
    }
}

Tip: For more Google - java console progress bar

TheMachineCharmer
I would add that JLine works very well for this sort of stuff
Brian Agnew