使用java写入控制台窗口中的相同位置 [英] Write to same location in a console window with java

查看:22
本文介绍了使用java写入控制台窗口中的相同位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在控制台窗口的同一位置写入一个字符.

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

推荐答案

在 Java 6 中,您可以使用 Console 来做这样的事情:

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 是特殊的退格字符.删除行上最后一个字符的打印.通过开始打印 | 然后在所有其他字符之前添加 u0008 ,您将获得微调器行为.

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.

请注意,这可能并非 100% 兼容所有控制台(并且 System.console() 可以返回 null).

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.

这篇关于使用java写入控制台窗口中的相同位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆