How to clear the console?

JavaConsole

Java Problem Overview


Can any body please tell me what code is used for clear screen in Java?

For example, in C++:

system("CLS");

What code is used in Java to clear the screen?

Java Solutions


Solution 1 - Java

Since there are several answers here showing non-working code for Windows, here is a clarification:

Runtime.getRuntime().exec("cls");

This command does not work, for two reasons:

  1. There is no executable named cls.exe or cls.com in a standard Windows installation that could be invoked via Runtime.exec, as the well-known command cls is builtin to Windows’ command line interpreter.

  2. When launching a new process via Runtime.exec, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls command gets redirected, it doesn’t clear the console.

To solve this problem, we have to invoke the command line interpreter (cmd) and tell it to execute a command (/c cls) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using inheritIO():

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}

Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.

Solution 2 - Java

You can use following code to clear command line console:

public static void clearScreen() {  
    System.out.print("\033[H\033[2J");  
    System.out.flush();  
}  

Caveats:

  • This will work on terminals that support ANSI escape codes
  • It will not work on Windows' CMD
  • It will not work in the IDE's terminal

For further reading visit this

Solution 3 - Java

This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).

public final static void clearConsole()
{
	try
	{
		final String os = System.getProperty("os.name");
		
		if (os.contains("Windows"))
		{
			Runtime.getRuntime().exec("cls");
		}
		else
		{
			Runtime.getRuntime().exec("clear");
		}
	}
	catch (final Exception e)
	{
		//  Handle any exceptions.
	}
}

⚠️ Note that this method generally will not clear the console if you are running inside an IDE.

Solution 4 - Java

Create a method in your class like this: [as @Holger said here.]

public static void clrscr(){
    //Clears Screen in java
    try {
        if (System.getProperty("os.name").contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        else
            Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

This works for windows at least, I have not checked for Linux so far. If anyone checks it for Linux please let me know if it works (or not).

As an alternate method is to write this code in clrscr():

for(int i = 0; i < 80*300; i++) // Default Height of cmd is 300 and Default width is 80
    System.out.print("\b"); // Prints a backspace

I will not recommend you to use this method.

Solution 5 - Java

A way to get this can be print multiple end of lines ("\n") and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.

Here is a sample code:

for (int i = 0; i < 50; ++i) System.out.println();

Solution 6 - Java

If you want a more system independent way of doing this, you can use the JLine library and ConsoleReader.clearScreen(). Prudent checking of whether JLine and ANSI is supported in the current environment is probably worth doing too.

Something like the following code worked for me:

import jline.console.ConsoleReader;

public class JLineTest
{
    public static void main(String... args)
    throws Exception
    {
        ConsoleReader r = new ConsoleReader();
        
        while (true)
        {
            r.println("Good morning");
            r.flush();
            
            String input = r.readLine("prompt>");
            
            if ("clear".equals(input))
                r.clearScreen();
            else if ("exit".equals(input))
                return;
            else
                System.out.println("You typed '" + input + "'.");
            
        }
    }
}

When running this, if you type 'clear' at the prompt it will clear the screen. Make sure you run it from a proper terminal/console and not in Eclipse.

Solution 7 - Java

Try the following :

System.out.print("\033\143");

This will work fine in Linux environment

Solution 8 - Java

Runtime.getRuntime().exec(cls) did NOT work on my XP laptop. This did -

for(int clear = 0; clear < 1000; clear++)
  {
     System.out.println("\b") ;
  }

Hope this is useful

Solution 9 - Java

By combining all the given answers, this method should work on all environments:

public static void clearConsole() {
    try {
        if (System.getProperty("os.name").contains("Windows")) {
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        }
        else {
            System.out.print("\033\143");
        }
    } catch (IOException | InterruptedException ex) {}
}

Solution 10 - Java

This will work if you are doing this in Bluej or any other similar software.

System.out.print('\u000C');

Solution 11 - Java

Try this: only works on console, not in NetBeans integrated console.

public static void cls(){
    try {

     if (System.getProperty("os.name").contains("Windows"))
         new ProcessBuilder("cmd", "/c", 
                  "cls").inheritIO().start().waitFor();
     else
         Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

Solution 12 - Java

You can use an emulation of cls with for (int i = 0; i < 50; ++i) System.out.println();

Solution 13 - Java

You need to use control characters as backslash (\b) and carriage return (\r). It come disabled by default, but the Console view can interpret these controls.

Windows>Preferences and Run/Debug > Console and select Interpret ASCII control characteres to enabled it

Console preferences in Eclipse

After these configurations, you can manage your console with control characters like:

\t - tab.

\b - backspace (a step backward in the text or deletion of a single character).

\n - new line.

\r - carriage return. ()

\f - form feed.

eclipse console clear animation

More information at: https://www.eclipse.org/eclipse/news/4.14/platform.php

Solution 14 - Java

You need to use JNI.

First of all use create a .dll using visual studio, that call system("cls"). After that use JNI to use this DDL.

I found this article that is nice:

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=5170&lngWId=2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsadiaView Question on Stackoverflow
Solution 1 - JavaHolgerView Answer on Stackoverflow
Solution 2 - JavasatishView Answer on Stackoverflow
Solution 3 - JavaDyndrilliacView Answer on Stackoverflow
Solution 4 - JavaAbhishek KashyapView Answer on Stackoverflow
Solution 5 - JavablackløtusView Answer on Stackoverflow
Solution 6 - JavaprungeView Answer on Stackoverflow
Solution 7 - JavaBhuvanesh WaranView Answer on Stackoverflow
Solution 8 - Javauser3648739View Answer on Stackoverflow
Solution 9 - JavaMuhammed GülView Answer on Stackoverflow
Solution 10 - JavaAbhigyan SinghView Answer on Stackoverflow
Solution 11 - JavaAadol RrashidView Answer on Stackoverflow
Solution 12 - JavaEpicView Answer on Stackoverflow
Solution 13 - JavaGrégori Fernandes de LimaView Answer on Stackoverflow
Solution 14 - JavaDennyView Answer on Stackoverflow