Re: How to delete the current line on console/command prompt?
Varying number of backspaces?
On Sun, 23 Aug 2009 11:57:44 +0000, Ulf Meinhardt wrote:
Assume I would like to output some dynamic textual information on the
command prompt/console about the state of (long lasting) computation.
I don't want to output for every while loop a new line. So I decide to
delete the current line until the start of the current line and output
the new information line.
How do I do this?
Just outputting backspaces does not help.
The trick is to output "\b \b", i.e. backspace over the end letter,
overwrite it with a space and than emit a second backspace to step back
past the space you just output. Here's an example:
public class Eraser
{
public static void main(String args[])
{
for (int n = 1; n <= 5; n++)
{
try
{
StringBuilder buff = new StringBuilder("Example line ");
for (int i = 0; i < n; i++)
buff.append("*");
String exLine = buff.toString();
System.out.print(exLine);
Thread.sleep(500);
for (int i = 0; i < exLine.length(); i++)
{
System.out.print("\b \b");
Thread.sleep(100);
}
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
return;
}
}
Its not really an SSCE: I had to put Thread.sleep() statements in so you
can see it working. Without either sleep its so fast at you think it
hasn't done anything and with just the sleep after the line was output
you can't see the erasure happen, giving the impression that asterisks
are being appended to the original line.
--
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |