使用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.
相关文章