views:

3044

answers:

3

Hello

In Java, how can I return to the start of a line and overwrite what has already been output on the console?

System.out.print(mystuff+'\r');

does not appear to work.

thanks in advance

+3  A: 

If you just want to write a new line to the console, you should use the println() method:

System.out.println(mystuff);

However, this will not delete what is already on the line. Actually, since System.out is a PrintStream, which is a type of OutputStream, that is basically hard to do, although you may find terminal-specific ways to do it.

You might have better luck using a Java implementation of a curses library, such as JavaCurses.

Avi
+2  A: 

My guess (And it is a guess) would be that '\r' does work, but the console you're using doesn't treat it as you'd expect. Which console are you using? If it's something like console output in your IDE, have you tried it on a real command-line instead?

izb
+7  A: 

I suspect that your cursor IS moving to the front of the line. The text you already have isn't disappearing because you haven't overwritten it with anything. You could output spaces to blank the line and then add another \r.

I just tested the following on Windows XP and AIX and it works as expected:

public class Foo {
  public static void main(String[] args) throws Exception {
   System.out.print("old line");
   Thread.sleep(3000);
   System.out.print("\rnew");
  }
}

I get "old line" printed, a 3 second delay, and then "old line" changes to "new line"

I intentionally made the first line longer than the second to demonstrate that if you want to erase the whole line you'd have to overwrite the end with spaces.

Also note that the "\b" escape sequence will back up 1 space, instead of to the beginning of the line. So if you only wanted to erase the last 2 characters, you could write:

System.out.println("foo\b\bun")

and get "fun".

mtruesdell
main() should catch exceptions! :D
schultkl
In real code, yes. In 3 lines testing behavior, not worth my time. :)
mtruesdell