What command in Java will let you clear the console in a command-line application?
clearing for bash that is working for me:
System.out.print(String.format("\033[H\033[2J"));
If none of the above solutions works for you( as in my case ), try this solution:
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
I'm using Windows 8 and this solution worked for me. Hope it does to you as well. :)
There is always the obvious (and kludgy)..
int numRowsInConsole = 60;
for (int ii=0; ii<numRowsInConsole; ii++) {
// scroll down one line
System.out.println("");
}
To my knowledge Windows 10's Command Window cmd.exe does not natively support ANSI ESC sequences, despite the rumors. To have the:
final String ANSI_CLS = "\u001b[2J";
System.out.print(ANSI_CLS);
method work you need a command line emulator that supports ANSI, such as ConEmu64.
I think what the OP wants is to clear the screen and move the cursor to the home position. For that try:
final String ANSI_CLS = "\u001b[2J";
final String ANSI_HOME = "\u001b[H";
System.out.print(ANSI_CLS + ANSI_HOME);
System.out.flush();
Run this sample program: it demonstrates how to clear the console using an escape sequence and reposition the cursor to position X=1, Y=1.
I tested it on several Linux terminals. Don't know, if it works under Windows.
Perhaps you can tell me ;)
Read this article about escape sequences.
import java.io.*;
public class Main {
public static final char ESC = 27;
public static void main(String[] args)
throws Exception {
Console c = System.console();
if (c == null) {
System.err.println("no console");
System.exit(1);
}
// clear screen only the first time
c.writer().print(ESC + "[2J");
c.flush();
Thread.sleep(200);
for (int i = 0; i < 100; ++i) {
// reposition the cursor to 1|1
c.writer().print(ESC + "[1;1H");
c.flush();
c.writer().println("hello " + i);
c.flush();
Thread.sleep(200);
}
}
}