Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 201
Akshu Avatar asked Aug 08 '14 18:08

Akshu


People also ask

What is Clrscr () in Java?

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) {} }

How do you clear a console?

Use the short cut Ctrl + L to clear the console. Use the clear log button on the top left corner of the chrome dev tools console to clear the console. On MacOS you can use Command + K button.

Can you clear console in Java Eclipse?

You can clear the console inside Eclipse using the 'Clear' command - it's accessible from the toolbar or the right-click menu...

Which code is used to clear the Consol?

clear() The console. clear() method clears the console if the console allows it.


1 Answers

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");
}
like image 168
Simply Craig Avatar answered Sep 30 '22 06:09

Simply Craig