Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to same location in a console window with java

Tags:

java

io

console

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

like image 754
user489041 Avatar asked May 02 '11 16:05

user489041


2 Answers

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.

like image 87
Henrik Gustafsson Avatar answered Oct 21 '22 14:10

Henrik Gustafsson


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

like image 23
MarcoS Avatar answered Oct 21 '22 14:10

MarcoS