Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear text printed on the Command Line with Java

Tags:

java

cmd

How I can clear text that prints in command line with Java? I want to clear Text1 after prints and overwrite with Text2. I search and find this code but it don't work.

public class className {

    public static void main(String[] args) throws IOException {
        System.out.println("Text1");
        Runtime.getRuntime().exec("cls");
        System.out.println("Text2");
    }
}
like image 323
Ehsan Avatar asked Feb 17 '13 17:02

Ehsan


People also ask

How do you clear the command line in Java?

Use ANSI Escape Codes to Clear Console in Java To clear the console in Java, we will use the escape code \033[H\033[2J . This weird set of characters represents the command to clean the console. To understand it better, we can break it down. The first four characters \033 means ESC or the escape character.

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

Can we use Clrscr in Java?

> java as clrscr() in c language. Use JNI to call clrscr. Or use exex to call an external CLR command.

How do I clear the console in command prompt?

From the Windows command line or MS-DOS, you can clear the screen and all commands using the CLS command.


1 Answers

You can do this with printing \b:

System.out.print("Text1");
System.out.print("\b\b\b\b\b");
System.out.print("     ");

Note that this will not work in Eclipse Console.

like image 80
partlov Avatar answered Sep 20 '22 10:09

partlov