I'm curious to know how to clear the console in Windows. I tried a few command, but nothing works
Runtime.getRuntime().exec("cls");
This didn't work for me.
I'd like to know if there is any method to clear the terminal in Java or if there is an external library to do this.
The link in answer by @Olivier does work but unfortunately most suggestions use a sub-process cls
or don't explain how to enable on Windows.
In latest Windows 10 you can use ANSI code support in Window Terminal, but not directly in CMD.EXE consoles. To enable for CMD.EXE add the registry key VirtualTerminalLevel
mentioned in these answers for ANSI colours and then you can print the appropriate ANSI/VT codes directly without running a sub-process:
System.out.print("\033[2J\033[1;1H");
Or
System.out.print(ANSI.CLEAR_SCREEN+ANSI.position(1, 1));
where simple definition of ANSI codes is:
public class ANSI {
// Control Sequence Introducer:
public static String CSI = "\u001b[";
public static String CLEAR_SCREEN = CSI+"2J";
public static String position(int row, int col) {
return CSI+row+";"+col+"H";
}
}
Note that other terminals or such as those in IDEs may not support the above.