Clear the console in Java

58,781

Solution 1

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") ;
}

Solution 2

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");
}
Share:
58,781
Akshu
Author by

Akshu

Updated on July 09, 2022

Comments

  • Akshu
    Akshu almost 2 years

    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.

  • Akshu
    Akshu almost 10 years
    as i have mentioned i am looking for more elegant way than printing blank lines :) .And I have tried both runtime methods it does not work.