Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

console

People also ask

How do you delete a line in C++?

The general format is ESC[X where ESC is the ASCII escape char ( 0x1b ), and X is the command.


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?


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.