How to Clear Screen in Java
In Java, when we compile and run Java programs, the console or screen gets messed up with lots of commands and output. To reduce or clear the messing content of the console, we need to clear the screen in Java so that we can execute programs in a proper way. In this section, we will learn how to clear the console or screen in Java.
There are the following ways to clear screen or console in Java:
Using ANSI Escape Code
ANSI escape sequence is standard in-band signaling to control the cursor position. In the following example, we have used the escape code \033[H\033[2J. Let's break the code and understand it separately.
On combining the above codes, we get \033[ or ESC[.
Let's combine the above two codes, we get \033[H\033[2J. The combination of code clears the screen or console.
The CSI commands use the default values if we do not specify any parameter in the command. We can use the following code to clear the screen in Java:
In the above example, we have used the same code (\033[H\033[2J) that we have explained above. It clears the console. We have also used the flush() function that resets the cursor position at the top of the screen.
Using Platform-Specific Command
We can also use the command according to the platform we are using. In this method, first, we get the property of the system by using the getProperty() method of the System class. After that, we select the command used in the platform to clear the console.
It is the static method of the System class. It is used to get the system property indicated by the specified key. It parses a parameter key of type String. It specifies the name of the system property. It returns the property of the system and
It throws the following exceptions:
Let's create a Java program that clears the console using the platform-specific command.
In the above example, we have specified the Windows operating system and the command that is used to clear the console is cls. We can also use the following code in the above program:
Using Command Line Interpreter
In this method, we invoke the command line interpreter (CMD). After invoking the interpreter executes the cls command. It allows executing the built-in commands. Now we need to connect the interpreter output channel with the Java process output channel. It can be done by using the inheritIO() method.
Once the above program connects with the console, it starts from a command line without output redirection and clears the screen or console.