9

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 /-\_/-\_/-\

user489041
  • 27,916
  • 55
  • 135
  • 204

2 Answers2

23

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.

Henrik Gustafsson
  • 51,180
  • 9
  • 47
  • 60
2

I don't think Java natively allows for that. You need to use some external library - maybe JCurses can help you.

Farbod Salamat-Zadeh
  • 19,687
  • 20
  • 75
  • 125
MarcoS
  • 13,386
  • 7
  • 42
  • 63