Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Clear Console in Java?

Tags:

java

console

I have been pulling my hair for this since quite long time. I have researched for an hour on how to clear a console in Java.

All I found was dirty hacking either by printing a bunch of lines or executing this

Runtime.getruntime.exec("cls/clear"); 

However, nothing seems to be working for me. Isn't there really any a way of clearing the console in Java like in C (clrscr();). Isn't there any external library by which this can be achieved.

Please let me know if anyone has ever done this before using a proper function, library etc. instead of dirty hacking.

like image 619
Pankaj Gadge Avatar asked Apr 20 '12 06:04

Pankaj Gadge


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 the console code?

Console clear() The clear() method clears the console. The clear() method also write "Console was cleared" in the console.

How do I clear the Java console in Eclipse?

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


1 Answers

If your terminal supports ANSI escape codes, this clears the screen and moves the cursor to the first row, first column:

System.out.print("\033[H\033[2J"); System.out.flush(); 

This works on almost all UNIX terminals and terminal emulators. The Windows cmd.exe does not interprete ANSI escape codes.

like image 63
Joni Avatar answered Oct 03 '22 00:10

Joni