在 Java 中清除控制台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25209808/
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
Clear the console in Java
提问by Akshu
I have a class extending the Thread class. In its run method there is a System.out.println
statement. Before this print statement is executed I want to clear the console. How can I do that?
我有一个扩展 Thread 类的类。在它的 run 方法中有一个System.out.println
声明。在执行此打印语句之前,我想清除控制台。我怎样才能做到这一点?
I tried
我试过
Runtime.getRuntime().exec("cls"); // and "clear" too
and
和
System.out.flush();
but neither worked.
但都没有奏效。
采纳答案by Start0101End
You can try something around these lines with System OS dependency :
您可以尝试使用 System OS 依赖来解决这些问题:
final String operatingSystem = System.getProperty("os.name");
if (operatingSystem .contains("Windows")) {
Runtime.getRuntime().exec("cls");
}
else {
Runtime.getRuntime().exec("clear");
}
Or other way would actually be a bad way but actually to send backspaces to console till it clears out. Something like :
或者其他方式实际上是一种糟糕的方式,但实际上将退格符发送到控制台直到它清除为止。就像是 :
for(int clear = 0; clear < 1000; clear++) {
System.out.println("\b") ;
}
回答by Simply Craig
Are you running on a mac? Because if so cls
is for Windows.
你是在mac上运行吗?因为如果cls
是 Windows。
Windows:
视窗:
Runtime.getRuntime().exec("cls");
Mac:
苹果电脑:
Runtime.getRuntime().exec("clear");
flush
simply forces any buffered output to be written immediately. It would not clear the console.
flush
只是强制立即写入任何缓冲输出。它不会清除控制台。
editSorry those clears only work if you are using the actual console. In eclipse there is no way to programmatically clear the console. You have to put white-spaces or click the clear button.
编辑抱歉,这些清除仅在您使用实际控制台时才有效。在 Eclipse 中,无法以编程方式清除控制台。您必须放置空格或单击清除按钮。
So you really can only use something like this:
所以你真的只能使用这样的东西:
for(int i = 0; i < 1000; i++)
{
System.out.println("\b");
}
回答by Bizi
Here is an example I found on a website hope it will work:
这是我在网站上找到的一个示例,希望它能起作用:
public static void clearScreen() {
System.out.print("3[H3[2J");
System.out.flush();
}