Write to same location in a console window with java

前端 未结 2 883
面向向阳花
面向向阳花 2020-12-16 03:58

I would like to write a character to the same location in a console window.

The characters I would like to write are / - \\ <

相关标签:
2条回答
  • 2020-12-16 04:37

    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.

    0 讨论(0)
  • 2020-12-16 04:41

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

    0 讨论(0)
提交回复
热议问题