Write to same location in a console window with java

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.

Tags:

Java

Io

Console