3

I have been on this for a while now, and for the past three days have ripped apart the Internet for ways to effectively clear the console in Java.

Ways I have seen it "done"

This way for(int x = 0; x!=100; x++){ System.out.println(); } Sucks, as you can just scroll up and see the printed statements again.

Console.Clear(); and all variations of it, have not worked for me.

Runtime.getRuntime().exec("cls"); has not worked in any cases i have tried to use it in.

(I use JCreator to code, I have no idea if this has anything to do with my issue)

This way by joesumbody122, looked interesting:

 private static void clearLine()
 {
       Console.Write(new string(' ', Console.BufferWidth - Console.CursorLeft));
 }

and

private static void clearLine(int left, int top)
{    

int pLeft = Console.CursorLeft;
int pTop  = Console.CursorTop;

Console.setCursorPosition(left, top);
Console.Write(new string(' ', Console.BufferWidth - Console.CursorLeft));

Console.setCursorPosition(pLeft, pTop);
}

But sadly i could not get it to work for me. It gave me errors that all the methods that he called from Console did not exist. java.io.*; was imported His method clears one line specifically, so if someone could get this working, (Again, I use JCreator to code, I have no idea if this has anything to do with my issue) I could see it being looped to clear all the lines.

Ways to make less sucky?

Back to this for(int x = 0; x!=100; x++){ System.out.println(); } Is there a way to prevent the user from scrolling up in the command line? To set the cursor to the top left of the prompt? That would make this method a whole lot more useful.

Another Theory

Is there a way to simply tell java to stop printing in one command line, start printing in another, and close the window of the first so it only appears to have cleared the console, but instead created an entirely new one? I have pondered this the last two hours, and in theory it would work, but i don't know if the code to do so even exists.

4

3 回答 3

3

没有一种可靠的方法可以在任何地方都有效。你已经发现了这一点。

通常,命令行输出进入终端回滚缓冲区,其中仅n显示最后一行,但前几行可通过滚动机制获得。命令行程序不会直接写入此缓冲区,而是stdout在大多数情况下通过管道将其写入终端进程,然后终端进程显示数据。

某些终端程序(即那些支持 ANSI 转义的程序)可能会让您清除屏幕的可见部分。据我所知,只有 Windows 的 cmd.exe 通过清除整个回滚缓冲区来响应“清除屏幕”请求。在 Linux AFAIK 上,不可能完全丢弃缓冲区。而且,在 Windows 上,cls它不是可执行命令,而是内置的 shell,因此您无法从 Java 运行它System.exec()

此外,任何命令行程序都可以在程序不知道的情况下将其输出重定向到文件,在这种情况下,“清除屏幕”没有多大意义。

如果您必须拥有这种级别的控制,那么您将不得不使用 Swing、AWT 或 GWT 或其他任何方式编写自己的显示窗口,并在那里管理所有交互。

于 2013-10-11T23:16:38.687 回答
1

如果它是一个命令行应用程序并且您运行该应用程序的终端/shell 支持 ANSI 转义码,那么您可以这样做:

System.out.print("\033[H\033[2J");
System.out.flush();
于 2013-10-11T17:11:14.160 回答
0

答案取决于天气,您使用的是 Linux 还是 Windows 操作系统。如果您使用的是 linux 并想清除控制台,请尝试:
try {
new ProcessBuilder("/usr/bin/clear").inheritIO().start().waitFor();
} catch(Exception e) {}

如果您使用的是 Windows,请尝试:
try {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
} catch(Exception e) {}

您可以以任何方式处理异常。没关系,因为您不会得到一个。

于 2021-01-04T23:34:49.460 回答