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");
}
}
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.
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) {} }
> java as clrscr() in c language. Use JNI to call clrscr. Or use exex to call an external CLR command.
From the Windows command line or MS-DOS, you can clear the screen and all commands using the CLS command.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With