I would like to write a character to the same location in a console window.
The characters I would like to write are /
-
\
_
. This will get me a little spinner I can display to show progress or loading.
How can you write the chars to the same location though? Otherwise, you will wind up with something like this /-\_/-\_/-\
With Java 6 you can use the Console
to do something like this:
class Main {
public static void main(String[] args) throws InterruptedException {
String[] spinner = new String[] {"\u0008/", "\u0008-", "\u0008\\", "\u0008|" };
Console console = System.console();
console.printf("|");
for (int i = 0; i < 1000; i++) {
Thread.sleep(150);
console.printf("%s", spinner[i % spinner.length]);
}
}
}
\u0008
is the special backspace character. Printing that erases the last character on the line. By starting to print a |
and then prepending the \u0008
before all other characters you get the spinner behavior.
Note that this might not be 100% compatible with all consoles (and that System.console()
can return null
).
Also note that you don't necessarily have to use the console class, as printing this sequence to standard output commonly works just as well.
I don't think Java natively allows for that. You need to use some external library - maybe JCurses can help you.
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