问题
I am working on a game that involves clearing the screen after each turn for readability. The only problem is I cannot use the Windows command prompt-based "cls" command and it does not support ANSI escape characters. I used Dyndrilliac's solution on the following page but it resulted in an IOException:
Java: Clear the console
Replacing "cls" with "cmd \C cls" only opened a new command prompt, cleared it, and closed it without accessing the current console. How do I make a Java program running through Windows Command Prompt access the command prompt's arguments and use them to clear its output?
回答1:
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
Solved here: Java: Clear the console
I realize this is an old post, but I hate when I find questions with responses of never mind i got it, or it just dies off. Hopefully it helps someone as it did for me.
Keep in mind it won't work in eclipse, but will in the regular console. take it a step further with if you're worried about cross OS:
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
回答2:
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) {}
}
回答3:
There's pretty much nothing in the console related API to do a clear screen. But, you can achieve the same effect through println()
s. A lot of putty clients clear the page like that and then scroll up.
private static final int PAGE_SIZE = 25;
public static void main(String[] args) {
// ...
clearScreen();
}
private static void clearScreen() {
for (int i = 0; i < PAGE_SIZE; i++) {
System.out.println();
}
}
回答4:
Create a batch file to clear the cmd screen and run your java program
Step 1. Create a file with extension .bat Step 2. So your code in batch file will be
Cls Cd desktop // path Javac filename.java // compiling Java desk // running
By doing this....you can clear the screen during run time
来源:https://stackoverflow.com/questions/19252496/clear-screen-with-windows-cls-command-in-java-console-application