Java:清除控制台

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2979383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:10:35  来源:igfitidea点击:

Java: Clear the console

javaconsoleclear

提问by sadia

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

任何人都可以告诉我Java中用于清除屏幕的代码是什么?例如在 C++ 中

system("CLS");

What code is used in Java for clear screen?

Java中使用什么代码来清除屏幕?

Thanks!

谢谢!

回答by blackl?tus

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.

一种方法是打印多个行尾(“\n”)并模拟清晰的屏幕。最后清楚,最多在unix shell中,不会删除以前的内容,只能向上移动,如果向下滚动可以看到以前的内容。

Here is a sample code:

这是一个示例代码:

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

回答by prunge

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

如果您想要一种更独立于系统的方式,您可以使用JLine库和ConsoleReader.clearScreen()。谨慎检查当前环境中是否支持 JLine 和 ANSI可能也是值得的。

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.

运行此程序时,如果您在提示符下键入“clear”,它将清除屏幕。确保从正确的终端/控制台而不是在 Eclipse 中运行它。

回答by 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).

这就是我将如何处理它。此方法适用于 Windows 操作系统案例和 Linux/Unix 操作系统案例(这意味着它也适用于 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 notclear the console if you are running inside an IDE.

请注意,如果您在 IDE 中运行,此方法通常不会清除控制台。

回答by user3648739

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

Runtime.getRuntime().exec(cls) 在我的 XP 笔记本电脑上不起作用。这确实——

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

Hope this is useful

希望这是有用的

回答by Denny

You need to use JNI.

您需要使用 JNI。

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

首先使用visual studio创建一个.dll,调用系统(“cls”)。之后使用 JNI 来使用这个 DDL。

I found this article that is nice:

我发现这篇文章很好:

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

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

回答by Epic

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

您可以使用模拟clsfor (int i = 0; i < 50; ++i) System.out.println();

回答by satish

You can use following code to clear command line console:

您可以使用以下代码清除命令行控制台:

public static void clearScreen() {  
    System.out.print("3[H3[2J");  
    System.out.flush();  
}  

For further references visit: http://techno-terminal.blogspot.in/2014/12/clear-command-line-console-and-bold.html

如需进一步参考,请访问:http: //techno-terminal.blogspot.in/2014/12/clear-command-line-console-and-bold.html

回答by Holger

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

由于这里有几个答案显示了 Windows 的非工作代码,这里有一个说明:

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

This command does notwork, for two reasons:

该命令没有工作,有两个原因:

  1. There is no executable named cls.exeor cls.comin a standard Windows installation that could be invoked via Runtime.exec, as the well-known command clsis 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 clscommand gets redirected, it doesn't clear the console.

  1. 在标准 Windows 安装中没有命名的cls.execls.com可以通过 调用的可执行文件Runtime.exec,因为众所周知的命令cls内置于 Windows 的命令行解释器中。

  2. 通过 启动新进程时Runtime.exec,标准输出被重定向到启动 Java 进程可以读取的管道。但是当cls命令的输出被重定向时,它不会清除控制台。

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

为了解决这个问题,我们必须调用命令行解释器 ( cmd) 并告诉它执行一个/c cls允许调用内置命令的命令 ( )。此外,我们必须将其输出通道直接连接到 Java 进程的输出通道,该通道从 Java?7 开始工作,使用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.

现在,当 Java 进程连接到控制台时,即从命令行启动而没有输出重定向,它将清除控制台。

回答by Abhigyan Singh

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

如果您在 Bluej 或任何其他类似软件中执行此操作,这将起作用。

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

回答by Abhishek Kashyap

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

在您的类中创建一个方法,如下所示:[正如@Holger在此处所说的那样。]

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).

这至少适用于 Windows,到目前为止我还没有检查过 Linux。如果有人检查它是否适用于 Linux,请告诉我它是否有效(或无效)。

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

另一种方法是在以下位置编写此代码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.

我不会推荐你使用这种方法。