One of the common tasks that a Java programmer may need to do is to clear the console or screen. It is beneficial for implementing interactive applications, debugging purposes, or simply refreshing the output. However, there is no built-in method in Java to clear the console or screen. Therefore, there must be alternate methods for achieving this functionality in Java.
By considering its need, this article will discuss different methods and will provide a practical implementation to clear the console/screen using Java.
Quick Outline
This article covers the following aspects:
- Method 1: Clear Console/Screen Using Different ANSI Escape Codes
- Method 2: Clear Console/Screen Using the ProcessBuilder Class
- Method 3: Clear Console/Screen Using the Console Class
- Deprecated version: Runtime Environment Class
Method 1: Clear Console/Screen Using Different ANSI Escape Codes
The ANSI escape codes are a special sequence of characters that enables the programmers to color, format, or control the output in the terminal. These codes instruct the terminal to perform a specific task when provided in conjunction with a text.
To clear the console in Java, follow the below examples using ANSI escape codes:
Example 1
The ANSI sequence specified clears the console and shifts the cursor back to the starting position. Inside the main() method, the print statement displays the following messages:
package clearConsole;
public class clearConsole {
public static void main(String[] args) //code for clearing the console
{
System.out.println("Welcome to JavaBeat");
System.out.println("\033[H\033[2J");
}
}
Here,
- “\033[H” moves the cursor to the starting position of the console.
- “\033[2J” clears the displayed content from the screen, terminal, or console.
Output
For executing the code file, navigate to the project directory and locate the “src” folder. Inside the folder, open CMD and provide the command mentioned-below to the terminal . Note that the placeholder “<JavaFileName>” should be replaced by your code file name:
java <JavaFileName>
The output is as follows:
Example 2
Another example of the ANSI sequences includes the “\u001b[2J]”. It shifts the cursor to the starting position of the console while clearing all the commands and output using the Java programming language:
package clearConsole;
public class clearConsole {
public static void main(String[] args)
{
System.out.println("Welcome to JavaBeat");
System.out.println("\u001b[2J" + "\u001b[H");
}
}
In the above-mentioned code:
- The “\u001b” represents a Unicode escape character. The “[2J” instructs the terminal to clear the screen.
- Next, the “[H” in the “\u001b[H” moves the cursor and positions it in the top-left corner of the console i.e., the home position.
Output
Inside the “src” folder of your Java project, open CMD to execute the code file. Replace the “<JavaFileName>” with the code file name and provide the following command to the terminal:
java <JavaFileName>
The output is given as follows:
Example 3
The ANSI escape sequences are represented in both Octal and Unicode notation. Another combination of octal notations that clears the console in Java is the “\033[“ with the “2J”.
The “\033[“ is an octal notation of the escape sequence that shifts the cursor to the start of the console. The “2J” clears all the commands and contents from the console:
package clearConsole;
public class clearConsole {
public static void main(String[] args) {
System.out.println("Welcome to JavaBeat");
System.out.println("\033[" + "2J");
}
}
Output
In the “src” folder of the Java project directory, open CMD. Replace the placeholder “<JavaFileName>” with your code file name and provide the following command to ther terminal:
java <JavaFileName>
The output is given as follows:
Example 4
In this example, the octal notation of the escape sequence “\033” is used with the “\143” that clear the console. The sequence “\143” in ASCII represents the “c” character. This combination of the ANSI sequence clears the console and shifts the cursor to the home position:
package clearConsole;
public class clearConsole {
public static void main(String[] args)
{
System.out.println("Welcome to JavaBeat");
System.out.println("\033\143");
}
}
Output
Within the Java project directory, open CMD inside the src folder. Provide the following command to the terminal after replacing the placeholder “<JavaFileName>” with your code file name:
java <JavaFileName>
The output is given below:
Example 5
As shown in the above example, the escape code “\033” can be directly used with the character “c” instead of specifying the ASCII code “\143”. Below is the code for this functionality:
package clearConsole;
public class clearConsole {
public static void main(String[] args)
{
System.out.println("Welcome to JavaBeat");
System.out.println("\033c");
}
}
Output
To execute the code file, replace the placeholder “<JavaFileName>” with your code file name and provide the following command to CMD inside the “src” folder of Java project:
java <JavaFileName>
The output is shown as below:
Example 6
Lastly, use the given ANSI sequences to clear the console or terminal using Java. In this code, the “\u001B” is the Unicode representation of the escape characters. On the other hand, the “[2J” clears the contents from the console or terminal:
package clearConsole;
public class clearConsole {
public static void main(String[] args)
{
System.out.println("Welcome to JavaBeat");
System.out.println("\u001B[2J");
}
}
Output
Within the Java folder directory, locate the “src” folder and provide the following command to terminal after making required modifications:
java <JavaFileName>
The output is given below:
Method 2: Clear Console/Screen Using the ProcessBuilder Class
The ProcessBuilder class provides multiple functions to create the processes of operating systems. In Java, the process builder class is used to clear the console:
package clearConsole;
import java.lang.System.*;
public class clearConsole {
public static void main(String[] args)
{
System.out.println("Clear the console using ProcessBuilder class");
String os = System.getProperty("os.name");
try {
if(os.startsWith("Windows")) // for Windows OS
{
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); //provide commands
}
else if(os.startsWith("Linux")) // For linux users
{
new ProcessBuilder("clear").inheritIO().start().waitFor();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
In the given code:
- The string variable “os” stores the operating system’s name which is returned by the System.getproperty() function.
- Inside the try block, the if-else statements check the specified conditions and execute the given logic.
- For instance, the if-statement condition is met and executed. Then, the “new ProcessBuilder()” creates a process of an operating system.
- The “inheritIO()” process ensures the same Java process is executed. In other words, it inherits the process for input and output operations.
- The “start()” method starts the process created by the ProcessBuilder class.
- Then, the program is in a waiting state due to the wait() function. It allows the thread to complete processing.
- Finally, the catch block display exception via the print statement.
Output
Inside the “src” folder of the Java project directory, open CMD. Then, replace the placeholder “<JavaFileName>” with your code file name:
java <JavaFileName>
The output of the code is given below:
Method 3: Clear Console/Screen Using the Console Class
In this example, the Console class is used to clear the terminal or screen. It provides various methods to read or write operations via the terminal. The code is as follows:
package clearConsole;
import java.lang.Runtime.*; //imports the Runtime class
import java.lang.Thread.*;
import java.io.*;
public class clearConsole {
public static void main(String[] args) {
Console c = System.console();
try {
c.writer().println("Clear Console Using Console Class ");
c.writer().print("\033[H\033[2J");
c.flush();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
In the above-given code:
- The necessary dependencies and classes are imported using the import statement such as Runtime, Threads etc.
- Inside the main() method, a Console class object “c” is created to invoke the functions.
- The try-catch block handles exceptions in Java and prevents the program from abnormal termination. Within this, the writer() method displays the message that will be cleared after the code execution.
- The ANSI sequence “\033[H\033[2J” clears the console and shifts the pointer to the top-left corner of the terminal.
- The catch block will display the error onto the console in case of any exception and the program will exit.
Output
Inside the “src” folder, open CMD and replace the “<JavaFileName>” with your code file name. Provide the command to CMD for execution:
java <JavaFileName>
The output is given as follows:
Deprecated Version: Runtime Class
The “java.lang.Runtime” provides different methods to work with the runtime environment of Java. With this class, developers can perform runtime-related tasks such as memory management, system processes, available processors, etc.
The Runtime.getRuntime().exec() accepts the commands for the execution. The usage of this method is discouraged as it is no longer supported by Java. You can use ProcessBuilder or ANSI escape codes for clearing the console using Java:
package clearConsole;
import java.lang.Runtime.*;
public class clearConsole {
public static void main(String[] args)
{
try {
System.out.println("Clear the console using Deprecated class");
String cmd= "cmd /C cls";
Runtime.getRuntime().exec(cmd);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
That is all from this guide.
Final Thoughts
To clear the console, screen, or terminal in Java, use different ANSI escape codes and methods. Oftentimes, when the Java programs are compiled via the terminal using the command, the console gets populated with different output, exceptions, or commands. It reduces readability and is problematic for keeping track of the program execution.
The ANSI escape codes are an efficient method for clearing the console. However, developers can also use the ProcessBuilder class for this purpose. This article has discussed different methods and provides a practical application of these methods for clearing a Console using Java.