How to Clear Console in Java?

console, java

Solution

If your terminal supports ANSI escape codes, this clears the screen and moves the cursor to the first row, first column:

System.out.print("\033[H\033[2J");
System.out.flush();

This works on almost all UNIX terminals and terminal emulators. The Windows `cmd.exe` does not interprete ANSI escape codes.

Problem

I have been pulling my hair for this since quite long time. I have researched for an hour on how to clear a console in Java. All I found was dirty hacking either by printing a bunch of lines or executing this ``` Runtime.getruntime.exec("cls/clear"); ``` However, nothing seems to be working for me. Isn't there really any a way of clearing the console in Java like in C (`clrscr();`). Isn't there any external library by which this can be achieved. Please let me know if anyone has ever done this before using a proper function, library etc. instead of dirty hacking.

Original source

Related problems