Monday, February 5, 2024

Clear Screen

Sometimes when you're writing a program in Java you want to clear the screen. That is to remove all text from the screen.

Here's how we would do this in Java:

private void clearScreen() {
        try {
            if (System.getProperty("os.name").contains("Windows")) {
                new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
            } else {
                new ProcessBuilder("clear").inheritIO().start().waitFor();
            }
        } catch (IOException | InterruptedException ex) {
            ex.printStackTrace();
        }
    }

This takes into account both windows and non windows. cls for Windows, clear for linux etc.

No comments:

Post a Comment

Ever feel like no one is listening?

 Ever have that feeling that no one is listening to you? Yeah, that feeling. It can be a strong feeling to have, a hurtful feeling also. The...