📅  最后修改于: 2023-12-03 15:15:55.666000             🧑  作者: Mango
In Java, clearing the console screen is not as straightforward as in some other programming languages. This guide explains various methods to clear the console screen in a Java program.
public class ClearConsole {
public static void main(String[] args) {
System.out.print("\033[H\033[2J");
System.out.flush();
}
}
Note: This method works on consoles that support ANSI escape sequences, such as most Unix-based terminals and some modern Windows terminals.
import java.io.IOException;
public class ClearConsole {
public static void main(String[] args) {
try {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Note: This method clears the console by executing the system command cls
on Windows or clear
on Unix-based systems.
#include <jni.h>
JNIEXPORT void JNICALL Java_ClearConsole_clearConsole(JNIEnv *env, jclass obj) {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
public class ClearConsole {
public static native void clearConsole();
static {
System.loadLibrary("ClearConsole");
}
public static void main(String[] args) {
clearConsole();
}
}
Note: This method requires writing native code in C and using JNI to invoke it from Java. It clears the console by executing the system command cls
on Windows or clear
on Unix-based systems.
These are some of the methods to clear the console screen in a Java program. Depending on the platform and the requirements of your application, you can choose the method that suits you best.