To clear the command line interface (CLI) screen in Java, you can use the following code:
public class Main { public static void main(String[] args) { // Clear the screen using ANSI escape codes System.out.print("\033[H\033[2J"); System.out.flush(); } }Source:www.lautturi.com
This code uses ANSI escape codes to move the cursor to the top-left corner of the screen and clear the screen. The \033
is the escape character, and the [H
and [2J
codes move the cursor and clear the screen, respectively.
Note that ANSI escape codes may not work on all systems, so you may need to use a different method to clear the screen depending on the environment.
Here are some other ways you can clear the CLI screen in Java:
public class Main { public static void main(String[] args) { // Clear the screen using the "cls" command try { new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); } catch (Exception e) { e.printStackTrace(); } } }
public class Main { public static void main(String[] args) { // Clear the screen using the "clear" command try { new ProcessBuilder("bash", "-c", "clear").inheritIO().start().waitFor(); } catch (Exception e) { e.printStackTrace(); } } }
Note that these methods involve running external processes, which may not be possible in all environments.