Java how to clear cli screen

Java how to clear cli screen

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:w‮‬ww.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:

  • On Windows, you can use the following code to clear the screen:
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();
        }
    }
}
  • On Unix-like systems, you can use the following code to clear the screen:
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.

Created Time:2017-11-03 22:21:03  Author:lautturi