Clear screen with Windows "cls" command in Java console application

greatmastermario picture greatmastermario · Oct 8, 2013 · Viewed 35.6k times · Source

I am working on a game that involves clearing the screen after each turn for readability. The only problem is I cannot use the Windows command prompt-based "cls" command and it does not support ANSI escape characters. I used Dyndrilliac's solution on the following page but it resulted in an IOException:

Java: Clear the console

Replacing "cls" with "cmd \C cls" only opened a new command prompt, cleared it, and closed it without accessing the current console. How do I make a Java program running through Windows Command Prompt access the command prompt's arguments and use them to clear its output?

Answer

Sean picture Sean · Nov 4, 2015
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();

Solved here: Java: Clear the console

I realize this is an old post, but I hate when I find questions with responses of never mind i got it, or it just dies off. Hopefully it helps someone as it did for me.

Keep in mind it won't work in eclipse, but will in the regular console. take it a step further with if you're worried about cross OS:

        final String os = System.getProperty("os.name");
        if (os.contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        else
            Runtime.getRuntime().exec("clear");