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

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

问题描述

我想在控制台窗口中将字符写入相同的位置。



我想写的字符是 / - \ _ 。这将给我一个微调器我可以显示以显示进度或加载。



如何写字符到同一个位置?否则,你会收到类似这样的 / - \ _ / - \ _ / - \

> Console 执行以下操作:

  Main {
public static void main(String [] args)throws InterruptedException {
String [] spinner = new String [] {\\\ /,\\\-,\ u0008 \\,\\\ | };
Console console = System.console();
console.printf(|);
for(int i = 0; i <1000; i ++){
Thread.sleep(150);
console.printf(%s,spinner [i%spinner.length]);
}
}
}

\\\ 是特殊的退格字符。打印擦除行上的最后一个字符。通过开始打印 | ,然后在所有其他字符之前加上 \\\ ,就可以得到微调框的行为。 / p>

请注意,这可能不是100%兼容所有控制台(和 System.console() 可以返回 null )。



还要注意,你不必使用控制台类,因为将这个序列打印到标准输出通常也是一样。


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

解决方案

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.

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

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