How can I return to the start of a line in a console?

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”.

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?

Leave a Comment