Clear console in Java

I have a class that extends the Thread class. Its execution method has an operator System.out.println

. Before this print statement is executed, I want to clear the console. How can i do this?

I tried

Runtime.getRuntime().exec("cls"); // and "clear" too  

      

and

System.out.flush(); 

      

but none of them worked.

+3


source to share


2 answers


You can try something around these lines with System OS dependencies:

final String operatingSystem = System.getProperty("os.name");

if (operatingSystem .contains("Windows")) {
    Runtime.getRuntime().exec("cls");
}
else {
    Runtime.getRuntime().exec("clear");
}

      



Or another way would actually be bad, but actually send backspaces to the console until it clears. Something like:

for(int clear = 0; clear < 1000; clear++) {
    System.out.println("\b") ;
}

      

+2


source


Are you on a Mac? Because if so cls

for Windows.

Window:

Runtime.getRuntime().exec("cls");

      

Mac:

Runtime.getRuntime().exec("clear");

      



flush

just forcibly writes any buffered output. It will not clear the console.

edit Sorry these cleanups only work if you are using the actual console. There is no way in eclipse to programmatically clear the console. You have to put white spaces or press the clear button.

So, you can really only use something like this:

for(int i = 0; i < 1000; i++)
{
    System.out.println("\b");
}

      

+4


source







All Articles