Is there any practical usage for \r
and \b
in Java? Could someone give an example w开发者_JAVA百科here it's used?
Formfeed escape is \f
, not \r
. The former is useful for clearing the screen in a console, whilst the second is useful for progress displays (as stated by aioobe).
\b
can be used in progress displays also, for example, on a ICMP Ping, you could display a dot when a ping is sent and a \b
when it is received to indicate the amount of packet loss.
I usually use \r
together with System.out.print
when printing some progress percentage.
Try running this in your terminal:
class Test {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 100; i++) {
System.out.print("Progress: " + i + " %\r");
Thread.sleep(100);
}
}
}
Form feed is \f
and \r
is carriage return.
\f
is used for printing characters after it from new line starting just below previous character.
System.out.println("This is before\fNow new line");
System.out.println("TEXTBEFORE\rOverlap");
System.out.println("12\b3");
Output:
This is before
Now new line
OverlapORE
13
Form feed is a page-breaking ASCII control character. It forces the printer to eject the current page and to continue printing at the top of another. Often, it will also cause a carriage return. For further details click here
精彩评论