Tuesday, October 13, 2009

How to print output on the same line on the console in Java?

Trying to continuously print output onto the same line in a console using Java?

Try this:
System.out.print("TEST TEXT\r");

The "\r" (carriage return) character returns the cursor to the beginning of the output line.

Just remember that if you do System.out.print("TESTTEXT\r"); and then System.out.print("BLAH\r");, your final output will be
BLAHTEXT

This is because the remaining characters from the longest string are not deleted after the shorter string overwrites it. Hence try to do something like this to delete of all characters from the longest string:
System.out.print("TESTTEXT\r"); //write text and go back to beginning of line
System.out.print(" \r"); //have many empty spaces to overwrite the chars from the longest string and then go back to the beginning of the line
System.out.print("BLAH\r"); //write text and go back to the beginning of the line

This will output:
BLAH

No comments:

Post a Comment

Thank you for your comment.