178

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

For example, in C++:

system("CLS");

What code is used in Java to clear the screen?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
sadia
  • 1,953
  • 5
  • 17
  • 17

14 Answers14

129

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

dialex
  • 2,706
  • 8
  • 44
  • 74
satish
  • 1,571
  • 1
  • 11
  • 4
  • 3
    Care to add to this at all? What is this string and do you need to flush if autoflush is enabled? – cossacksman Nov 03 '15 at 00:24
  • 9
    They are [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). Specifically [clear screen, followed by home](https://paulschou.com/tools/ansi/java-0047.html). But why is 'home' necessary? – jdurston Nov 12 '15 at 20:01
  • 2
    @jdurston omitting home will not reset the cursor back to the top of the window. –  Sep 21 '16 at 11:35
  • 2
    Doesn't work in Eclipse, but work in Linux terminal. One vote for you – Anh Tuan Nov 07 '16 at 09:15
  • 15
    This only works if the terminal emulator in which Java runs, supports ANSI escape codes. Windows NT/XP/7/8/10 CMD doesn't – Thorbjørn Ravn Andersen Sep 17 '17 at 23:16
  • @ThorbjørnRavnAndersen, you mean the Windows console. CMD is a shell, not a console or terminal. – Eryk Sun Jan 16 '19 at 19:27
  • @eryksun The thing that comes up when you ask Windows to invoke "CMD". If it can be invoked in a way that supports ANSI codes on all Windows machines, I'd love to hear about it. – Thorbjørn Ravn Andersen Jan 17 '19 at 11:41
  • @ThorbjørnRavnAndersen, CMD is a shell that uses a console, just like the bash shell in Linux uses a terminal. The difference with Windows is that executables can be flagged as console applications in the PE image header, in which case the process initialization code in kernelbase.dll will automatically attach to or allocate a console, depending on whether the parent has a console and whether the process creation flags override the default behavior by forcing no console (detached) or a new console. So people run CMD and see a console pop up, and then *mistakenly* think that CMD is the console. – Eryk Sun Jan 17 '19 at 11:57
  • @ThorbjørnRavnAndersen, as to virtual terminal support (i.e. VT escape codes), this was added to the console in Windows 10. In previous versions getting VT support requires an alternative console that hacks/hooks the console API, such as ConEmu or ANSICON. – Eryk Sun Jan 17 '19 at 12:01
  • @eryksun You may want to write that up in a full answer somewhere. Glad to hear it was added in Windows 10 - only been missing since NT 4.0 or something like that. – Thorbjørn Ravn Andersen Jan 17 '19 at 12:07
  • 2
    @ErykSun Windows 10 now supports ANSI codes, but enables them only for executables with a flag, for compatibility reasons. Since `java.exe` doesn’t have that flag, simple `System.out.print` statements still get no ANSI support. However, if you launch an executable or command that has that flag, e.g. a simple `echo` command, it works. – Holger Nov 13 '19 at 17:27
  • @Holger, if virtual terminal support isn't enabled, it's a simple matter to enable it via `GetConsoleMode` (get the current mode of the screen buffer) and `SetConsoleMode` to add the `ENABLE_VIRTUAL_TERMINAL_PROCESSING` flag. From Java there's the added complexity of JNI to call the latter functions. A user can also enable this setting globally in the console default settings in "HKCU\Console". Set a DWORD value of 1 as the "VirtualTerminalLevel". – Eryk Sun Nov 14 '19 at 01:56
  • 1
    @ErykSun which brings us back to square one, the absence of a simple Java solution. – Holger Nov 14 '19 at 08:35
  • I could not get the "clear" command to work via Java in the Vs code terminal on Linux, but this worked for me. Thanks! – Matt Feb 03 '20 at 15:05
  • Worked at Windows 10 using Visual Studio Code as IDE. – Ricardo Maroquio Oct 16 '20 at 18:08
129

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.

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
Holger
  • 285,553
  • 42
  • 434
  • 765
  • 1
    Why this not work for me? I running the program on windows CMD but the screen its not cleared – Alist3r Mar 22 '16 at 14:23
24

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.

dialex
  • 2,706
  • 8
  • 44
  • 74
Dyndrilliac
  • 765
  • 9
  • 16
  • 11
    On Windows 8.1: `java.io.IOException: Cannot run program "cls": CreateProcess error=2, The system cannot find the file specified` – Ky - Oct 21 '14 at 20:30
  • 1
    @BenLeggiero That error occurs if for some reason the cls command isn't found by the JVM within some directory from the PATH environment variable. All this code does is call the Windows or Unix system command based on the default system configuration to clear the command prompt or terminal window respectively. It should be exactly the same as opening a terminal window and typing "cls" followed by the Enter key. – Dyndrilliac Oct 21 '14 at 22:34
  • I know all this, but I figured it's worth noting that it can still fail. I don't know _why_ it failed, but it obviously can. – Ky - Oct 22 '14 at 20:00
  • were you testing it in the console of an IDE? – brainmurphy1 Nov 05 '14 at 00:22
  • For me testing it in an IDE it does not work and throws an exception. It also does not work when running it outside of the IDE from the command line on Windows 8.1 and Java 8. – danielcooperxyz Dec 03 '14 at 11:42
  • 28
    There is no `cls` executable in Windows. It is an **internal** command of `cmd.exe`. –  Mar 26 '15 at 13:35
  • 7
    As said by others, [doesn’t work at all](http://stackoverflow.com/a/33379766/2711488), not only because Windows has no cls executable, but also because the output of subprocesses gets redirected. – Holger Oct 27 '15 at 22:55
  • 2
    This answer is also a topic on meta see: http://meta.stackoverflow.com/questions/308950/what-to-do-if-voting-based-qa-does-not-work-at-all – Petter Friberg Oct 28 '15 at 20:35
20

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();
blackløtus
  • 899
  • 1
  • 8
  • 15
  • 16
    A faster way to accomplish this is printing a single string of 50 `\r\n` with a single `println`, since there's a noticeable delay between `println` calls. – Ky - Oct 22 '14 at 20:01
  • 10
    How do you know how many lines the console is configured to display? Might work in most cases, but not all. – Cypher Oct 28 '15 at 20:47
  • 5
    The biggest difference between this and a proper `clear` is that in the latter, the new output will be at the top of the screen and not the bottom. – ndm13 Jul 12 '16 at 01:50
  • I have to use 70 iterations to clear the screen completely. – adeen-s Feb 26 '17 at 16:46
  • 8
    `System.out.println(new String(new char[50]).replace("\0", "\r\n"));` will do the job faster and better. – Aaron Esau Dec 30 '17 at 00:28
  • 3
    @AaronEsau starting with JDK 11, you can use `System.out.println(System.lineSeparator().repeat(50));` – Holger Nov 13 '19 at 17:30
20

Try the following :

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

This will work fine in Linux environment

Bhuvanesh Waran
  • 593
  • 12
  • 28
17

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.

Community
  • 1
  • 1
Abhishek Kashyap
  • 3,332
  • 2
  • 18
  • 20
15

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
prunge
  • 22,460
  • 3
  • 73
  • 80
8

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

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

Hope this is useful

Neuron
  • 5,141
  • 5
  • 38
  • 59
user3648739
  • 113
  • 1
  • 1
7

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) {}
}
Muhammed Gül
  • 825
  • 10
  • 19
4

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) {}
}
Gunesh Shanbhag
  • 559
  • 5
  • 13
Md Adilur Rashid
  • 700
  • 7
  • 13
3

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

System.out.print('\u000C');
Community
  • 1
  • 1
0

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

Epic
  • 113
  • 1
  • 12
0

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

-2

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

Denny
  • 97
  • 7