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.
In Java, System. out. println() is a statement which prints the argument passed to it. The println() method display results on the monitor. Usually, a method is invoked by objectname.
System. out. println is an IO-operation and therefor is time consuming. The Problem with using it in your code is, that your program will wait until the println has finished.
You could print the backspace character \b
as many times as the characters which were printed before.
System.out.print("hello");
Thread.sleep(1000); // Just to give the user a chance to see "hello".
System.out.print("\b\b\b\b\b");
System.out.print("world");
Note: this doesn't work flawlessly in Eclipse console in older releases before Mars (4.5). This works however perfectly fine in command console. See also How to get backspace \b to work in Eclipse's console?
Clearing screen in Java is not supported, but you can try some hacks to achieve this.
a) Use OS-depends command, like this for Windows:
Runtime.getRuntime().exec("cls");
b) Put bunch of new lines (this makes ilusion that screen is clear)
c) If you ever want to turn off System.out, you can try this:
System.setOut(new PrintStream(new OutputStream() {
@Override public void write(int b) throws IOException {}
}));
You could use cursor up to delete a line, and erase text, or simply overwrite with the old text with new text.
int count = 1;
System.out.print(String.format("\033[%dA",count)); // Move up
System.out.print("\033[2K"); // Erase line content
or clear screen
System.out.print(String.format("\033[2J"));
This is standard, but according to wikipedia the Windows console don't follow it.
Have a look: http://www.termsys.demon.co.uk/vtansi.htm
I am using blueJ for java programming. There is a way to clear the screen of it's terminal window. Try this:-
System.out.print ('\f');
this will clear whatever is printed before this line. But this does not work in command prompt.
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