Akshu
Akshu

Reputation: 69

Clear the console in Java

I have a class extending the Thread class. In its run method there is a System.out.println statement. Before this print statement is executed I want to clear the console. How can I do that?

I tried

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

and

System.out.flush(); 

but neither worked.

Upvotes: 5

Views: 66844

Answers (3)

Bizi
Bizi

Reputation: 69

Here is an example I found on a website hope it will work:

 public static void clearScreen() {
    System.out.print("\033[H\033[2J");
    System.out.flush();
}

Upvotes: 0

Start0101End
Start0101End

Reputation: 108

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

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

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

Or other way would actually be a bad way but actually to send backspaces to console till it clears out. Something like :

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

Upvotes: 2

Simply Craig
Simply Craig

Reputation: 1114

Are you running on a mac? Because if so cls is for Windows.

Windows:

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

Mac:

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

flush simply forces any buffered output to be written immediately. It would not clear the console.

edit Sorry those clears only work if you are using the actual console. In eclipse there is no way to programmatically clear the console. You have to put white-spaces or click the clear button.

So you really can only use something like this:

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

Upvotes: 5

Related Questions