5

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.

Joel
  • 4,732
  • 9
  • 39
  • 54
Akshu
  • 69
  • 1
  • 1
  • 5
  • You need to use [Eclipse's API](http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fui%2Fconsole%2Factions%2FClearOutputAction.html) for that. – PM 77-1 Aug 08 '14 at 18:24
  • 1
    possible duplicate of [How to delete stuff printed to console by System.out.println()?](http://stackoverflow.com/questions/7522022/how-to-delete-stuff-printed-to-console-by-system-out-println) – PM 77-1 Aug 08 '14 at 18:27
  • I don't want to use a series of printing blank lines method. i need a more elegant way of clearing out console.If any please let me know. – Akshu Aug 08 '14 at 18:43
  • The simple print cannot do this. You need to tell the surrounding terminal emulator to do this, which under Unix and DOS typically is done with escape sequences, but which CMD.EXE does not support. How much control do you have of the surrounding terminal emulator? – Thorbjørn Ravn Andersen Aug 08 '14 at 22:48
  • duplication: http://stackoverflow.com/questions/2979383/java-clear-the-console – OhadR May 03 '15 at 12:39

3 Answers3

4

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");
}
Simply Craig
  • 1,084
  • 1
  • 10
  • 18
2

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") ;
}
Thiht
  • 252
  • 4
  • 11
Start0101End
  • 108
  • 5
  • 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. – Akshu Aug 08 '14 at 19:15
0

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();
}
Bizi
  • 69
  • 1
  • 8