I am developing a command-line interface (CLI) tool in Java and I need to refresh the display by clearing the console buffer. I have tried using various print statements, but they just scroll the text up rather than actually clearing the screen. Is there a standard System call or a Runtime execution command that works reliably across Windows, macOS, and Linux without needing external libraries like JLine or Lanterna?
3 answers
Clearing the console in Java is notoriously tricky because the language is designed to be platform-independent, but console control is OS-specific. For Windows, you generally have to invoke the system shell using new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();. On Unix-like systems such as Linux or macOS, you can use the ANSI escape code \033[H\033[2J which moves the cursor to the home position and clears the screen. A robust solution usually involves checking the os.name system property first to determine which command to execute. Just keep in mind that these methods often fail within IDE consoles like Eclipse or IntelliJ, which don't support full TTY emulation.
That ProcessBuilder approach for Windows seems a bit heavy just to clear some text. If I am writing a simple student project, is there a risk that calling cmd /c cls will slow down the application's performance significantly if I'm refreshing the screen multiple times per second, like for a terminal-based game?
The simplest way that works for most modern terminals is just printing \033[H\033[2J and then flushing the output stream. It’s clean and doesn't require complex process handling.
I agree with Nancy. I used this exact method in my last Java project. As Thomas mentioned in the original post, just remember that this won't look like it's working if you're only looking at the output window inside your IDE; you have to run it in a real terminal!
Steven, you've hit on a major performance bottleneck. Spawning a new process every frame is extremely expensive in terms of CPU cycles. For a terminal game, you're much better off using ANSI escape sequences. Even on modern Windows 10 and 11, the virtual terminal processing can be enabled, allowing you to use the much faster escape codes. This avoids the overhead of launching cmd.exe entirely, which is essential for smooth frame rates in a CLI environment.