7

How I can clear text that prints in command line with Java? I want to clear Text1 after prints and overwrite with Text2. I search and find this code but it don't work.

public class className {

    public static void main(String[] args) throws IOException {
        System.out.println("Text1");
        Runtime.getRuntime().exec("cls");
        System.out.println("Text2");
    }
}
Sean Owen
  • 66,182
  • 23
  • 141
  • 173
Ehsan
  • 2,273
  • 8
  • 36
  • 70
  • 2
    You should read this http://www.javaworld.com/jw-12-2000/jw-1229-traps.html and this http://alvinalexander.com/java/java-exec-processbuilder-process-1 – duffymo Feb 17 '13 at 17:57
  • 2
    This is not possible. System.out is ***not*** a terminal, it is just an output stream. – le3th4x0rbot Feb 17 '13 at 17:57
  • 1
    [link](http://sourceforge.net/projects/javacurses/) – le3th4x0rbot Feb 17 '13 at 17:59
  • Most terminal support VT100 commands. You can try to use them. [VT-100 commands](http://www.braun-home.net/michael/info/misc/VT100_commands.htm) – MrSmith42 Feb 17 '13 at 18:04
  • Most solutions are system dependent and problematic. Perhaps there are other options? Why do you want to clear the output in the first place? – Axel Feb 17 '13 at 18:29
  • @Axel I want to create a animated text in command line, so I try to clean previous position of text – Ehsan Feb 17 '13 at 18:35

3 Answers3

8

You can do this with printing \b:

System.out.print("Text1");
System.out.print("\b\b\b\b\b");
System.out.print("     ");

Note that this will not work in Eclipse Console.

partlov
  • 13,789
  • 6
  • 63
  • 82
  • 2
    Sorry, a forgot one thing. `\b` just returns cursor one place back, so you need just to print spaces in it. I tested this in windows cmd and it works. Notice I used `print` not `println`! – partlov Feb 17 '13 at 18:40
3

Try this solution:

new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();

I'm using Windows 8 and this solution worked for me. Hope it does to you as well. :)

2

You can simply use '\r' (carriage return) escape sequence.

System.out.print("Text1");
System.out.print("\rText2");

Would only print 'Text2'

Konrad G
  • 419
  • 7
  • 14