Wie lösche ich die Konsole mit Java?

Lesezeit: 6 Minuten

Benutzeravatar von sadia
Sadia

Kann mir bitte jemand sagen, welcher Code zum Löschen des Bildschirms in Java verwendet wird?

Zum Beispiel in C++:

system("CLS");

Welcher Code wird in Java verwendet, um den Bildschirm zu löschen?

  • stackoverflow.com/questions/606086/…

    – Vanuan

    2. Februar 2011 um 20:07 Uhr

Benutzeravatar von Holger
Holger

Da es hier mehrere Antworten gibt, die nicht funktionierenden Code für Windows zeigen, hier eine Klarstellung:

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

Dieser Befehl tut es nicht Arbeit, aus zwei Gründen:

  1. Es gibt keine ausführbare Datei mit dem Namen cls.exe oder cls.com in einer Standard-Windows-Installation, die über aufgerufen werden könnte Runtime.execwie der bekannte Befehl cls ist in den Befehlszeileninterpreter von Windows integriert.

  2. Beim Starten eines neuen Prozesses über Runtime.exec, wird die Standardausgabe an eine Pipe umgeleitet, die der initiierende Java-Prozess lesen kann. Aber wenn die Ausgabe der cls Der Befehl wird umgeleitet, die Konsole wird nicht gelöscht.

Um dieses Problem zu lösen, müssen wir den Kommandozeileninterpreter aufrufen (cmd) und ihm sagen, dass es einen Befehl ausführen soll (/c cls), mit der integrierte Befehle aufgerufen werden können. Außerdem müssen wir seinen Ausgabekanal direkt mit dem Ausgabekanal des Java-Prozesses verbinden, der ab Java 7 funktioniert 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();
    }
}

Wenn nun der Java-Prozess mit einer Konsole verbunden ist, dh von einer Befehlszeile ohne Ausgabeumleitung gestartet wurde, löscht er die Konsole.

  • Warum funktioniert das bei mir nicht? Ich führe das Programm auf Windows CMD aus, aber der Bildschirm wird nicht gelöscht

    – Alist3r

    22. März 2016 um 14:23 Uhr

Benutzeravatar von satish
satt

Sie können den folgenden Code verwenden, um die Befehlszeilenkonsole zu löschen:

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

  • Care to add to this at all? What is this string and do you need to flush if autoflush is enabled?

    – cossacksman

    Nov 3, 2015 at 0:24

  • They are ANSI escape codes. Specifically clear screen, followed by home. But why is ‘home’ necessary?

    – jdurston

    Nov 12, 2015 at 20:01


  • @jdurston omitting home will not reset the cursor back to the top of the window.

    – user3714134

    Sep 21, 2016 at 11:35

  • Doesn’t work in Eclipse, but work in Linux terminal. One vote for you

    – Anh Tuan

    Nov 7, 2016 at 9: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, 2017 at 23:16

Dyndrilliac's user avatar
Dyndrilliac

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.

  • On Windows 8.1: java.io.IOException: Cannot run program "cls": CreateProcess error=2, The system cannot find the file specified

    – Ky –

    Oct 21, 2014 at 20:30


  • @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, 2014 at 22:34

  • There is no cls executable in Windows. It is an internal command of cmd.exe.

    – a_horse_with_no_name

    Mar 26, 2015 at 13:35

  • As said by others, doesn’t work at all, not only because Windows has no cls executable, but also because the output of subprocesses gets redirected.

    – Holger

    Oct 27, 2015 at 22:55

  • This answer is also a topic on meta see: meta.stackoverflow.com/questions/308950/…

    – Petter Friberg

    Oct 28, 2015 at 20:35

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();

Bhuvanesh Waran's user avatar
Bhuvanesh Waran

Try the following :

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

This will work fine in Linux environment

  • It should be on the top! Worked on Linux console.

    – Zahid Khan

    Sep 13, 2020 at 6:58

  • Thank you! Worked on Linux, Android and Mac OS X.

    – Max Pierini

    Dec 2, 2021 at 17:40

  • Worked on windows too!

    – discape

    Jan 30 at 6:25

  • This worked for me in windows using vscode terminal, but DID NOT work when exported as a .jar

    – The Big Kahuna

    Apr 21 at 15:53

Community's user avatar
Community

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) {}
}

Dies funktioniert zumindest für Windows, ich habe es bisher nicht für Linux überprüft. Wenn jemand es für Linux überprüft, lassen Sie mich bitte wissen, ob es funktioniert (oder nicht).

Als alternative Methode können Sie diesen Code in schreiben 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

Ich werde Ihnen diese Methode nicht empfehlen.

  • Es sollte oben sein! Arbeitete auf der Linux-Konsole.

    – Zahid Khan

    13. September 2020 um 6:58 Uhr

  • Danke schön! Funktioniert unter Linux, Android und Mac OS X.

    – Max Pierini

    2. Dezember 2021 um 17:40 Uhr

  • Hat auch an Windows funktioniert!

    – entkommen

    30. Januar um 6:25 Uhr

  • Dies funktionierte für mich in Windows mit dem vscode-Terminal, funktionierte jedoch NICHT, wenn es als .jar exportiert wurde

    – Die große Kahuna

    21. April um 15:53 ​​Uhr

Benutzeravatar von Neuron
Neuron

Wenn Sie dies auf eine systemunabhängigere Weise tun möchten, können Sie die verwenden JLine Bibliothek u ConsoleReader.clearScreen(). Vorsichtig prüfen, ob JLine und ANSI werden unterstützt im aktuellen Umfeld lohnt sich wahrscheinlich auch.

So etwas wie der folgende Code hat bei mir funktioniert:

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 + "'.");
            
        }
    }
}

Wenn Sie dies ausführen und an der Eingabeaufforderung „clear“ eingeben, wird der Bildschirm gelöscht. Stellen Sie sicher, dass Sie es von einem geeigneten Terminal / einer geeigneten Konsole und nicht in Eclipse ausführen.

1450000cookie-checkWie lösche ich die Konsole mit Java?

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy